【问题标题】:Is there a way to ignore Handlebars templates within a Handlebars template?有没有办法忽略 Handlebars 模板中的 Handlebars 模板?
【发布时间】:2012-12-02 04:30:29
【问题描述】:

我在我的服务器端节点应用程序中使用 Express + Handlebars,我想将客户端模板作为我正在呈现的页面的一部分发送到浏览器。

index.html

<html>
<head>
  <title>{{title}}</title>
</head>
<body>
  <div>
    {{stuff}}    
  </div>
  <script id="more-template" type="text/x-handlebars-template">
    <div>{{more}}</div>
  </script>
</body>

不幸的是,handlebars 尝试在 #more-template 脚本块中渲染内容。 (这只是删除了{{more}},因为它在服务器模板的上下文中未定义。

有没有办法让它忽略脚本标签内的东西?(以便客户端模板可以使用它)

我已经看到了这个问题:Node.js with Handlebars.js on server and client,我宁愿只使用 1 个模板引擎。

【问题讨论】:

    标签: node.js handlebars.js


    【解决方案1】:

    一般来说,当您的模板被编译两次时(例如,当您只是服务器端时)并且您想在第一次运行时忽略模板标签,您可以简单地通过附加反斜杠来告诉车把忽略它们:

    {{variable1}} \{{variable2}}
    

    编译时将variable1 设置为value1 并且variable2 未定义,您会得到:

    value1 {{variable2}}
    

    (而不是将第二个标签替换为空字符串)。

    在将variable2 设置为value2 的情况下编译第二次运行时,您会得到:

    value1 value2
    

    不是完美的解决方案(这将是 Handlebars 单独保留未定义变量的设置),但适用于我的特殊情况。

    【讨论】:

    【解决方案2】:

    所以我没有找到轻松忽略客户端模板的方法,但普遍的共识是预编译您的客户端模板。

    1. 全局安装车把npm install handlebars -g
    2. 预编译您的模板handlebars client-template1.handlebars -f templates.js
    3. 包含templates.js &lt;script src="templates.js"&gt;&lt;/script&gt;
    4. 执行模板var html = Handlebars.templates["client-template1"](context);

    额外信息
    Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
    http://handlebarsjs.com/precompilation.html

    【讨论】:

    • 正是我想要的。在玩了很多地方之后,我发现这是最简单、最适合我的东西的解决方案。
    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多