For a new project we're writing documentation about the Django template system. We use Django for the documentation project itself too, so Django picks up all our example variables in the sample code and tries to render them. The only way we found to get around this is to use {% templatetag %}, but that makes our code really unreadable. Is there maybe a way to make Django ignore all template variables in a specific section?
Django 1.5 solves this problem with the verbatim template tag. It also works fine with the current Django versions.
{% verbatim myblock %}
Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
{% endverbatim myblock %}
Due to limitations in the Django template lexer (like being a kludgy hack), this is impossible. However, if you are willing to put your example code in separate files, you can use the ssi
tag:
{% ssi /path/to/my/code/examples/example01.html %}
And it won't parse the file, just include it verbatim. However, this also has limitations in that you can't use variables in the include path (i.e. if you move template locations, you have to rewrite or at least find-and-replace your template files), and you have to put the include path (i.e. /path/to/my/code/examples
) in the ALLOWED_INCLUDE_ROOTS
setting in your settings.py
. (See http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi.)
A possible solution is to write the templates as usual (with {{ x }}
), but save them as .txt (or any other extension you want). Write a script the runs over these files, and automatically creates the .html for you, by doing the reverse of templatetag (replacing {{
with {% templatetag openvariable %}
etc). Make sure the code runs after you update the templates.
I solved this by adding an "include_raw" template tag that behaves like the built-in "include" tag, but just doesn't parse or process the file passed to it. I'm running Django 1.2 under App Engine.
Create a tags module (tags.py):
from django.template import loader
from google.appengine.ext.webapp import template
register = template.create_template_register()
@register.simple_tag
def include_raw(path):
return loader.find_template(path)[0]
Register it:
from google.appengine.ext.webapp import template
template.register_template_library("tags")
Use it:
{% include_raw "this-will-be-included-verbatim.html" %}
If your source is HTML, the easiest solution would be to replace "{" and "}" with their respective HTML entities:
{
becomes {
}
becomes }
Example:
<code>
To include some other file, you can use the {% include %} template tag.
To include a variable, use {%{% varname }%}%.
</code>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With