24

I need to produce an id surrounded by braces ( for example "{1234}" ). With the django template language, braces are also used to start a variable substitution, so I have some trouble in obtaining what I want. I tried

{{{ id }}}
{{ '{'id'}' }}
{{ '{'+id+'}' }}
{ {{ id }} }

None of these methods work, except the last one, which unfortunately produces "{ 1234 }", not what I want. I currently have two solutions : either I pass an id variable already containing the {} (ugly) or I write a custom filter and then write {{ id|add_braces }} (I prefer it).

Before going this way, I prefer to ask if a better solution exists.

Using escaped values does not work. Even if I add {% autoescape off %}%7B{% endautoescape %} I don't get the {, which is strange, but that's another problem.

Thanks

Edit: I wrote a quick filter. Pasting it here so someone else can use it as a template for writing a more complex one. To be put into python package application_path/templatetags/formatting.py

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def add_braces(value):
    return "{"+value+"}"
Stefano Borini
  • 138,652
  • 96
  • 297
  • 431

3 Answers3

30

I think your answer can be found here:

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag

In short, you want to use {% templatetag openbrace %} and {% templatetag closebrace %}.

Edit: Django now also includes this functionality out of the box:

{% verbatim %} {{ blah blah }} {% endverbatim %}
Paul McMillan
  • 19,693
  • 9
  • 57
  • 71
10

{% templatetag openbrace %} become extremely verbose for e.g. javascript templates

I've used the verbatim tag from this gist with some success for exactly this purpose which lets you do something like

{{ request.user }}
{% verbatim %}
     brackets inside here are left alone, which is handy for e.g. jquery templates
     {{ this will be left }}
     {% so will this %}
{% endverbatim }}

{% more regular tags (to be replaced by the django template engine %}
bstpierre
  • 30,042
  • 15
  • 70
  • 103
second
  • 28,029
  • 7
  • 75
  • 76
  • the verbatim template tag is now part of django (1.5): https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#verbatim – stephendwolff Jun 30 '13 at 20:29
  • The accepted answer on this question should probably be changed - verbatim really is the right way to do this now. – shacker Apr 23 '14 at 23:20
1

The recommendation from the Jinja templating language works with the Django templating engine as well:

http://jinja.pocoo.org/docs/dev/templates/#escaping

The solution is this:

{{ '{' }}{{ id }}{{ '}' }}

Of course the other two answers work, but this is one is less verbose and more readable, in my opinion.

freb
  • 1,151
  • 13
  • 28
  • 1
    For small verbatim values, this is a good solution. For large blocks, I'd go with the `{% verbatim %}` block tag. – Rebs Nov 10 '15 at 05:44