Code should be readable.
Recently, I had to make some changes to some XML that had been written in a Django template. To avoid the xml being rendered by the browser as HTML, the code had been manually escaped, thus making the code rather unreadable.
Sorry, no views
The various documentation templates were being rendered using direct_to_template so I couldn’t move the XML to a view and let Django’s autoescaping take over. Besides, the XML is legitamately part of the static content of the page and shouldn’t be in the view.
Custom filters can be very misleading
So I decided to write a custom filter to escape the XML as needed. But I kept running into this error:
‘my_filter’ is not a valid tag library: Could not load template library from django.templatetags.doc_code, No module named my_filter
Which made me think I had a path issue, or a misplaced file, or a missing __init__.py. But all my initial guesses checked out. Turns out that django spits out a ‘No module’ error when there are errors in the filter code. Very misleading.
Now it’s looking good
So the final result is a django template that looks like this:
<p>Here's some XML:</p> {% filter xmldoc %} <children> <child>Koes</child> <child>Chris</child> </children> {% endfilter %}
And the custom filter looks like this:
from django.template import Library from django.template.defaultfilters import stringfilter from xml.sax.saxutils import escape register = Library() @register.filter @stringfilter def xmldoc(value): return escape(value).strip() xmldoc.is_safe = True
Now the XML is readable to the users and the developers.
My sources
A coworker was wrestling with this exact same problem. This should help out quite a bit, thanks!
[...] say you would like to post some XML in a blog post about, for example, XML in a Django template. There’s a great plugin called WP-Syntax that adds syntax highlighting to code samples in [...]