chriscauley
chriscauley

Reputation: 20991

Escape HTML in Jinja2

I'm writing my blog using jinja2. Many of my blog articles contain html snippets as code examples, but replacing < and > with &gt; and &lt; is tedious and annoying. I want to do something like this:

<pre><code class="html">
  {% escapehtml %}
  <div>This is how you make a div</div>
  {% endescapehtml %}
</pre></code>

I'd like the result to render the pre and code tags, but escape the div. I've tried using autoescape, verbatim, and raw, but none of them seem to do what I want (I believe they center around javascript and jinja's {{}} escaping). Is there a built in way to do this? Do I need to write my own template tag?

Upvotes: 1

Views: 2251

Answers (1)

Ryon Sherman
Ryon Sherman

Reputation: 1583

Filter sections allow you to apply regular Jinja2 filters on a block of template data.

Just wrap the code in the special filter section:

<pre><code class="html">
  {% filter escape %}
  <div>This is how you make a div</div>
  {% endfilter %}
</pre></code>

Upvotes: 2

Related Questions