Is there a way to ignore Handlebars templates within a Handlebars template?

久未见 提交于 2019-12-01 04:17:09

问题


I'm using Express + Handlebars in my server side node application, and I want to send client templates to the browser as part of the page that I'm rendering.

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>

Unfortunately, handlebars tries to render the stuff in the #more-template script block. (Which just removes the {{more}} because it's undefined in the server template's context.

Is there a way I can get it to ignore the stuff inside the script tag? (So that the client side template can use it)

I already saw this question: Node.js with Handlebars.js on server and client, I'd rather just use 1 template engine.


回答1:


In General, when your template is being compiled two times (e.g. when you are only server-side) and you want to ignore template tags in the first run, you can simply tell handlebars to ignore them by appending a backslash:

{{variable1}} \{{variable2}}

When compiling with variable1 set to value1 and variable2 being undefined, you get:

value1 {{variable2}}

(instead of getting the second tag replaced with empty string).

When compiling the second run with variable2 set to value2, you get:

value1 value2

Not the perfect solution (which would be a setting for Handlebars to leave undefined variables alone), but working for my special case.




回答2:


So I didn't find a way to ignore client templates easily, but the general consensus is to precompile your client templates.

  1. Install handlebars globally npm install handlebars -g
  2. Precompile your templates handlebars client-template1.handlebars -f templates.js
  3. Include templates.js <script src="templates.js"></script>
  4. Execute the template var html = Handlebars.templates["client-template1"](context);

Extra info
Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
http://handlebarsjs.com/precompilation.html



来源:https://stackoverflow.com/questions/13874161/is-there-a-way-to-ignore-handlebars-templates-within-a-handlebars-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!