Ever wondered how to include {{ or {% in the output of a Django template? The answer is to use the {% templatetag .. %} template tag:

@register.tag
def templatetag(parser, token):
    """
    Outputs one of the bits used to compose template tags.

    Since the template system has no concept of "escaping", to display one of
    the bits used in template tags, you must use the ``{% templatetag %}`` tag.

    The argument tells which template bit to output:

        ==================  =======
        Argument            Outputs
        ==================  =======
        ``openblock``       ``{%``
        ``closeblock``      ``%}``
        ``openvariable``    ``{{``
        ``closevariable``   ``}}``
        ``openbrace``       ``{``
        ``closebrace``      ``}``
        ``opencomment``     ``{#``
        ``closecomment``    ``#}``
        ==================  =======
    """

For example:

{% templatetag openvariable %}foo.bar{% templatetag closevariable %} = {{ foo.bar }}

renders to:

{{ foo.bar }} = somevalue

(Another sneaky way might be to use the ssi tag, but I wouldn't recommend it.)

View Django documentation entry.


comments powered by Disqus



Learn how to speed up your Django site — get your FREE 14-day course

Become an expert in high-performance web applications.