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.
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?
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…
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 %}.
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