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+"}"
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 %}
{% 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 %}
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.
Related
For me this works:
{{ game.description|safe }}
But this fails:
{{ game.description|safe|slice:"65" }}
Is there a way to apply two or more filters on a variable in Django templates?
Although it's quite past when the OP posted the question, but for other people that may need the info, this seems to work well for me:
You can rewrite
{{ game.description|safe|slice:"65" }}
as
{% with description=game.description|safe %}
{{description|slice:"65"}}
{% endwith %}
Is description an array or a string?
If it is a string, you might want to try truncatewords (or truncatewords_html if the description can contain HTML),
{{ game.description|safe|truncatewords:65 }}
Reference: Built-in filter reference, truncatewords.
(I'm new to Django so my apologies if slice works on strings.)
change
{{ game.description|safe|slice:"65" }}
to
{{ game.description|safe|slice:":65" }}
you are missing the colon
This may work:
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in all lowercase.
{% endfilter %}
Reference: Built-in tag reference, filter.
I'm working on rendering a form template. The relevant code is something like this:
{% for field in filter.form %}
{% if field.is_hidden %}
{{ field }}
{% else %}
<div class="field">
{{ field }}
</div>
{% endif %}
{% endfor %}
So far, so good. If it's a hidden field, just display the field. If not, put a div wrapper with the class field to activate some CSS from the framework I'm using.
However, I need that class in the div wrapper to be picker if the field is a select box. It needs to be picker-multiple if it's a select multiple box. And so on.
Is this possible to do in the template view? We're working with a framework (which is why I don't want to just target the form fields differently with CSS), but we'd like the core code to work without the framework (which, I think, is why we wouldn't want to do this sort of thing in the separate Python file).
As for what I've tried, I noticed that {{ field.field.widget }} renders something like <django.forms.widgets.Select object at 0x10d822a50>. I would have then expected {{ field.field.widget.Select }} to render something (True came to mind), but it does nothing.
django-widget-tweaks includes field_type and widget_type template filters for you.
I believe you have to use a custom template tag as detailed here. This answer explains a similar issue with a solution using custom template tag.
I was using the count method on a queryset context variable more than once in a template, so I decided to store it in a reusable variable:
{% with album.photograph_set.count as numPhotos %}
<title>My title with {{ numPhotos }} in it</title>
<span>I use {{ numPhotos }} here, too</span>
{% endwith %}
The numPhotos variable always seems to be blank, though replacing it with album.photograph_set.count inline still returns the appropriate value. I also tried using the {% with numPhotos=album.photograph_set.count %} syntax but it exhibits the same behavior. I use the {% with ... as ... %} syntax elsewhere in my code and it works as expected.
Any help is appreciated.
If photograph_set is the reverse relationship of a ForeignKeyField or if it's a ManyToManyField, you'll need to do
{% with album.photograph_set.all.count as numPhotos %}
I want to do this:
{% for egg in eggs %}
<p>{{ egg.spam }}</p>
{% if egg.is_cool %}
{% myvariable = egg %} // Possible in any way?
{% endif %}
{% endfor %}
Pardon the JavaScript-style comment (it shows up as a comment on SO)
I think the closest you'll get is the with tag: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#with.
If you're say trying to feature an item in a template, I can imagine doing something like:
<div class="special">
{% with some_list.first as special_item %}
{{ specialitem }}
{% endwith %}
</div>
<div class="everything">
{% for item in some_list %}
{{ item }}
{% endfor %}
</div>
If you want some special logic to determine which one is the special item, I'd add a method to the object (so you end up with: {% with some_collection.my_method as special_item %} above) or determine the special item before passing it to the view. Hope that helps.
Welcome to Django Templates.
This problem is easily solved with one of the earliest snippets posted to DjangoSnippets.com: the Expr tag.
People can argue all day about the separation of logic from the templates, but that ignores that there is business logic, which belongs in the models or views, and presentation logic which belongs only in the templates. If you have a lot of presentation logic you may want to consider using Jinja2 for some or all of your templates. WARNING: although Jinja2 looks a lot like Django's template language, there are incompatibilities with things like Custom Template Tags.
Yes, you can use the with construct:
{% with myvariable as egg %}
do stuf
{% endwith %}
I think it's probably best to do this kind of test-and-set behaviour in the view, not the template. If anything, it'll give you better control over cacheing if/when you need it.
I'm trying to build a blog app and the problem is when I use tag 'truncatewords_html' in my template to truncate posts longer than specified number of words, I need to link to complete post by some title like 'read more...' after truncation. So I should know that the post was truncated or not.
P.S.: Is this a pythonic way to solve the problem?
{% ifequal post.body|length post.body|truncatewords_html:max_words|length %}
{{ post.body|safe }}
{% else %}
{{ post.body|truncatewords_html:max_words|safe }}read more
{% endifequal %}
This is pretty convoluted but django has some weird corners. Basically I figure if the string length is the same if you truncate at x and x+1 words then the string has not been truncated...
{% ifnotequal post.body|truncatewords_html:30|length post.body|truncatewords_html:31|length %}
read more...
{% endifnotequal %}
You could write a custom template tag (see django docs), or manually check in the template, whether the content you want to display exceeds the given length via length builtin filter.
It comes down to personal preference, but for my taste you're doing way too much work in the template. I would create a method on the Post model, read_more_needed() perhaps, which returns True or False depending on the length of the text. eg:
def read_more_needed(self):
from django.utils.text import truncate_html_words
return not truncate_html_words(self.body,30)==truncate_html_words(self.body,31)
Then your template would read:
{% if post.read_more_needed %}
{{ post.body|truncatewords_html:30|safe }}read more
{% else %}
{{ post.body|safe }}
{% endif %}
Check out http://code.djangoproject.com/ticket/6799
This patch provides a method to replace the default elipses for truncated text.