How Jinja2 and Handlebars.js can Co-Exist
I'm relatively new to Handlebars.js, but in my learning process I came across a pretty interesting pitfall. Both Jinja2 and Handlebars.js (and Mustache.js, I suppose) use the same syntax for token-replacement: {{ expression }}
.
What was proving tricky was when I wanted to use server-side data a la Jinja2 in my Handlebars templates. How does the server know when it's supposed to do token-replacement and when it's supposed to leave it alone for later? Use {% raw %}
:
{{ jinja2 expressions here }}
{% raw %}
{{ handlebars expressions here }}
{% endraw %}
{{ jinja2 expressions here }}
{% raw %}
Tells Jinja2 to leave alone whatever's inside, kind of like HTML's <pre>
tag.
This means that you should wrap your <script type="text/x-handlebars-template">
tags in {% raw %}
tags up to the point where you need Jinja2 to take over, and then "re-raw" your template. For instance:
{% raw %}
<script type="text/x-handlebars-template">
<div>
<h1>{{title}}</h1>
<a href="{% endraw %}{{ getSomeUrl() }}{% raw %}">
{{ linkText }}
</a>
</div>
</script>
{% endraw %}
Written by Jason Edelman
Related protips
4 Responses
THANK YOU!
I was so worried there wasn't a solution!
You're welcome :) glad I could help!
Nice post. Kicking myself for not realizing this was my issue earlier :)
Nice one! I was about to give up on handlebars before this. Thanks very much.