117

I serve dynamic pages from Jinja2 templates in Flask. Now I am defining client-side templates in say, Jinja2-clone Nunjucks inside a script tag. Problem is, the client-side templates has syntax like <% %> that Flask's Jinja2 interpreter may interpret instead of rendering verbatim.

How can I make the entire block of scripts render verbatim?

Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202

1 Answers1

261

You can disable interpretation of tags inside a {% raw %} block:

{% raw %}

Anything in this block is treated as raw text,
including {{ curly braces }} and
{% other block-like syntax %}

{% endraw %}

See the Escaping section of the template documentation.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Is it possible to escape `{% endraw %}` line ? – Vlad Havriuk Jul 24 '21 at 14:50
  • 6
    @Vlad: not really, no. Don’t use exactly that text inside a raw block. You can use `{{ "{" }}` **outside** of a raw block to insert a literal curly brace followed by `% endraw %}`. If you are generating HTML, you could use HTML entities, like `&lbrace;`, `&percnt;` and `&rbrace;` instead of `{`, `%` and `}`, respectively. – Martijn Pieters Jul 25 '21 at 01:26