5

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.

Community
  • 1
  • 1
Zachary Yates
  • 11,664
  • 7
  • 50
  • 84

2 Answers2

10

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.

deyhle
  • 433
  • 3
  • 9
  • This. Was. Helpful. Related post I made just in case: https://stackoverflow.com/questions/66533653/multiple-pass-variable-replacements-with-handlebars/66534342#66534342 – Nicholas Hazel Mar 08 '21 at 20:48
5

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

Community
  • 1
  • 1
Zachary Yates
  • 11,664
  • 7
  • 50
  • 84
  • Exactly what I was looking for. after juggling a lot of places, I found this the easiest and the best working solution for my stuff. – dhruvpatel Jun 28 '16 at 21:51