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.
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.
So I didn't find a way to ignore client templates easily, but the general consensus is to precompile your client templates.
npm install handlebars -g
handlebars client-template1.handlebars -f templates.js
<script src="templates.js"></script>
var html = Handlebars.templates["client-template1"](context);
Extra info
Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
http://handlebarsjs.com/precompilation.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With