Display code in a Django template

What’s the best practice here if I want to display, say, Python code within a Django template? For example if I want to do something crazy like have a Django-powered site with Django tutorials. Basically I want to escape it to just display without being run.

In Markdown I’d use {% raw %}{% endraw %} tags. But I’m finding that neither the template tags verbatim nor templatetag do this.

Is there any easy fix I’m missing here?

G’day Will,

If by Django template you mean the HTML templates that Django can render, can you not simply use HTML5’s <code> tag? Or have I completely misunderstood your question?

Cheers,

Conor

I’m using tags already. The issue is putting something like “{% block %}” within a template. Django seems to just treat them all as “code”. There should be a way to escape it somehow that I haven’t figured out…

Like what’s the Django equivalent of rendering code as I’d do in Markdown with “raw” tags like this:

<!-- templates/registration/login.html --> 
<h2>Login</h2> 
<form method="post"> 
  {% raw %}{% csrf_token %} 
  {{ form.as_p }}{% endraw %} 
  <button type="submit">Login</button> 
</form>

You can use {% templatetag %} to put literal template code in a Django template. Not a simple as just wrapping a block of code though. For that you want {% verbatim %}.

{% verbatim %} isn’t working for me. Still have same issue…

<pre><code>
{% verbatim %}
  <form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>
{% endverbatim %}
</pre></code>

This feels so silly to me. Must be a way to fully escape this.

Ok so using {% filter force_escape %} with {% verbatim %} tags around double brackets works. Super janky. Not something to do manually :slight_smile:

This is pretty much expected, I’d say – {% verbatim %} only stops the Django template engine from rendering the contents, but does not provide escaping. If you were to write the same content in plain HTML, you’d see the same result, so maybe I’m missing why you expect otherwise?

I’d probably pass the things you want to display as a string to the template, because this will remove the need for any tags (including verbatim). This is probably obvious to you and you have reasons to avoid it, I just wanted to mention it as an option.

<pre>
{{ my_example }}
</pre>

would be all that is needed. I suppose you could also turn django.utils.html.escape into a block level template tag, though!

I think the passing into the template approach is the correct one. Carlton Gibson recommended as much. I was more playing around with it all and I think, when I first asked the question, not thinking my best.

But it is the double whammy of escape content and then use verbatim to stop the Django template engine from rendering. Many ways to skin this cat.

I think simplest is use python-markdown and its extensions to auto-escape stuff, add Pygments, etc. But fun and educational to do from scratch :slight_smile: