Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 203
Zachary Yates Avatar asked Dec 14 '12 07:12

Zachary Yates


2 Answers

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.

like image 120
deyhle Avatar answered Sep 27 '22 22:09

deyhle


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

like image 28
Zachary Yates Avatar answered Sep 27 '22 22:09

Zachary Yates