Last Updated: February 25, 2016
·
11.53K
· ultimatedelman

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 %}

4 Responses
Add your response

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

over 1 year ago ·

You're welcome :) glad I could help!

over 1 year ago ·

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

over 1 year ago ·

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

over 1 year ago ·