fy6vka
Last Updated: February 25, 2016
·
9.295K
· ultimatedelman
0e2e822d32a7ab3d7f0b7098d03b1d16

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 %}
Say Thanks
Respond

4 Responses
Add your response

13628
D1a24df4a9671c439f9ed0c893472d10

THANK YOU!
I was so worried there wasn't a solution!

over 1 year ago ·
13640
0e2e822d32a7ab3d7f0b7098d03b1d16

You're welcome :) glad I could help!

over 1 year ago ·
17756
None

Nice post. Kicking myself for not realizing this was my issue earlier :)

over 1 year ago ·
26543
None

Nice one! I was about to give up on handlebars before this. Thanks very much.

over 1 year ago ·