How to escape {{ or }} in django template?

前端 未结 10 1899
慢半拍i
慢半拍i 2020-12-01 04:17

Django treats {{ var }} as some variable in its template. How can I escape {{ var }} or {{ or }} such that django does no

相关标签:
10条回答
  • 2020-12-01 04:48

    I believe you are looking for the templatetag template tag.

    As the linked-to doc states,

    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.

    For example:

    <p>"{% templatetag openvariable %} some text {% templatetag closevariable %}"</p>
    

    will appear as so:

    <p>"{{ some text }}"</p>
    
    0 讨论(0)
  • 2020-12-01 04:48

    Jinja, which is what is being used for the templates, offers several suggestions for escaping here. What has worked best for me is using something like "{% raw %}{{ some text }}{% endraw %}"

    0 讨论(0)
  • 2020-12-01 04:59

    Django 1.5 introduced {% verbatim %} template tag. It stops template from parsing contents of this tag:

    {% verbatim %}
        {{ var }}
    {% endverbatim %}
    

    will be rendered as:

    {{ var }}
    
    0 讨论(0)
  • 2020-12-01 05:03

    Edit: I don't really recommended this because it's not very clean, but it's still an option.

    I was searching for one that I could use with JQuery Templates and figured a way to do it without tags or filters. This is as short as I could get it:

    {{ "{{ any text }" }}}
    

    Is printed as:

    {{ any text }}
    

    Why it works? Any text within {{}} is displayed as is, as long as it doesn't have two closing braces }} in a row. Then there are three brackets in a row, django interprets two first ones as end of the variable leaving one additional closing brace.

    0 讨论(0)
提交回复
热议问题