index.html
<td>{% if place or other_place or place_description%}{{ place}} {{ other_place}} {{place_description}}</td>
This is displaying all the data in template.I want to truncate the string if it is more than length 80.
Conditions are,
1.If place variable have more than 80 character,it should truncate their and need not show the other two variable like other_place and place_description.
2.If place variable and other_place variable making more than 80 character,in this case it should truncate from place_variable don't need to show place_description variable.
3.If all the three are their and the 80th character is made from place_description,need to truncate from their.
All fields are not mandatory,so whatever field is comes to display,it should show only 80 character.
Need help to do this.
Thanks
You could use slice for pre-django 1.4:
{% if place or other_place or place_description%}
{% with place|add:other_place|add:place_description as pl %}
{% if pl|length > 80 %}
{{pl|slice:80}}...
{% else %}
{{pl }}
{% endif %}
{% endwith %}
{% endif %}
If you are using django 1.4 or greater,
You can just use truncatechars
{% if place or other_place or place_description%}
{% with place|add:other_place|add:place_description as pl %}
{{pl|truncatechars:80}}
{% endwith %}
{% endif %}
You could probably do it with a combination of add/truncatechars e.g.
{{ place|add:other_place|add:place_description|truncatechars:80}}
You could also use 'cut' which is part of django template builtins
for example if
{{ file.pdf.name}}
gives 'store/pdfs/verma2010.pdf'
{{ file.pdf.name | cut:'store/pdfs/'}}
Would give 'verma2010.pdf'
Took me way too long to find the answer in 2022. It's truncatechars, e.g.
{{ my_string|truncatechars:1 }}
https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#truncatechars
Related
A little question to jinja2 templating:
I want to create a reusable template to include and then overwrite blocks. Macros do not let me write junks of HTML easily as parameters do they? Say I want to reuse an include several times and am using BIG junks of HTML in blocks that I want to dynamically assign
how would I do it?
certainly not with macros I guess, or am I wrong?
{% render_foo('bar',2) %} is fine
{% render_foo('<table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc') %} is not fine any more is it
"what do you really want to do?"
yes, what I told you, I have a way I create containers for my data. The container is ALWAYS the same. The content is completely different on each usage. Once a table. Once a bootstrap component. Once a form.
The surrounding elements are always the same
to reproduce the simple error this is what I did:
{% include 'full_section.html' %}
{% block fullsection %} <table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc{% endblock %}
{% include 'full_section.html' %}
{% block fullsection %} <form>//some cool LONG big form </form>{% endblock %}
full_section.html contents just for completeness, it is a lot more complex in reality
<div class="my_cool_full_section">
{% block full_section %}{% endblock %}
</div>
TemplateAssertionError: block 'fullsection' defined twice
I found the answer well hidden in the jinja2 docs
http://jinja.pocoo.org/docs/2.9/templates/#block-assignments
so you use a macro and a block assignment e.g. like this:
{% set section_content %}
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
{% endset %}
{{ render_full_size_section(section_content) }}
{% set section_content %}
aaaaaaaaaaa
{% endset %}
{{ render_full_size_section(section_content) }}
wonder what they were doing pre 2.8... dark dark middle age
then in the macro:
{% macro render_full_size_section(content) %}
<div class="mycoolsection">
{{ content | safe }}
</div>
{% endmacro %}
I think the best way to describe is problem is with an example.
{% for content in contents %}
{% for stuff in {{content}} %}
{{stuff}}
{% endfor %}
{% endfor %}
I am using google app engine webapp templates. I can't seem to use a result from the parent forloop {{content}} as a variable for its child forloop. TemplateSyntaxError: Could not parse the remainder: '{{content}}' from '{{content}}' Is it possible to do this? Thanks!!
You can use only content without braces around:
{% for content in contents %}
{% for stuff in content %}
{{ stuff }}
{% endfor %}
{% endfor %}
When you are inside the first for-loop, content exists in the context, as any other variable. Same thing for stuff in the inner loop. Plus, blocks are generally using argument as variables, except in it is surrounded by quotes.
The {{ }} notation can be use to only display the variable in the document.
It is able to write {{ myval.add:5 }}, {{ myval|add:value }} and even {{ myval|add:-5 }}.
However, I can't find out what I should type to add value * -1 like {{ myval|add:-value }}. This doesn't work, sadly.
You need to use double quotes:
{{ myval|add:"-5" }}
This subtracts five from myval.
The built-in Django template tags/filters aren't all-encompassing, but it's super easy to write your own custom template tags: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
You could make your own subtract template tag pretty easily:
#register.filter
def subtract(value, arg):
return value - arg
Use django-mathfilters from PyPI: https://pypi.python.org/pypi/django-mathfilters
To install :
$ pip install django-mathfilters
Then add mathfilters in your INSTALLED_APPS.
In template:
{% load mathfilters %}
<ul>
<li>8 + 3 = {{ 8|add:3 }}</li>
<li>13 - 17 = {{ 13|sub:17 }}</li>
{% with answer=42 %}
<li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
{% endwith %}
{% with numerator=12 denominator=3 %}
<li>12 / 3 = {{ numerator|div:denominator }}</li>
{% endwith %}
<li>|-13| = {{ -13|abs }}</li>
</ul>
I recently started working with Django and stumbled upon this one as well: I needed a very simple template loop that stops printing after n times and shows a "more" link to toggle the rest of the items.
With great interest I read the struggle of people trying to understand why this is not being added to the Django default filters (since before 2013). I didn't feel like creating a custom template tag and I kind of found a way to subtract 2 variables using strings and add in combination with with and stringformat
Let's say I have a list of items where I want to print the first 2 and hide the rest, showing how many hidden items are there, eg.
John, Anna and 5 others like this (when given a list of 7 items)
As long as the number of visible items is harcoded in the template (eg. 2), it's possible to add the negative 2 |add:"-2", but I wanted the number of visible items to be a variable as well. The Math-filter library as suggested above doesn't seem up to date (I haven't tested it with Django 2.x).
The trick seems to be to use the add helper to concat the strings "-" with the integer as string, so it can be coerced back to a negative integer in a any consecutive calls to the add helper. This doesn't work however if the value is not a string, so that's where the stringformat helper comes in.
With string value
template posts.html (note how visible is explicitely passed as string - alternative below)
{% for post in posts %}
<h4>{{ post.title }}</h4>
...
{% include 'show_likes.html' with likes=post.likes visible="3" %}
{% endfor %}
template show_likes.html (note the add:0 to make the boolean operator work)
{% with show=visible|default:"2" %}
{% for like in likes %}
{% if forloop.counter <= show|add:0 %}
{% if not forloop.first %},{% endif %}
{{ like.username }}
{% endif %}
{% endfor %}
{% if likes|length > show|add:0 %}
{% with rest="-"|add:show %}
and {{ likes|length|add:rest }} more
{% endwith %}
{% endif %}
like this
{% endwith %}
Alternative with integer
You could just convert your integer to a string in the calling template using |stringformat:"d"
If however the number of visible items you want to show is an integer, you'll have to add a call to stringformat:"d" to have it converted to string
template posts.html
{% for post in posts %}
<h4>{{ post.title }}</h4>
...
{% include 'show_likes.html' with likes=post.likes visible=3 %}
{% endfor %}
template show_likes.html
{% with show=visible|default:2 %}
{% with show_str=show|stringformat:"d" %}
{% for like in likes %}
{% if forloop.counter <= show %}
{% if not forloop.first %},{% endif %}
{{ like.username }}
{% endif %}
{% endfor %}
{% if likes|length > show|add:0 %}
{% with rest="-"|add:show_str %}
and {{ likes|length|add:rest }} more
{% endwith %}
{% endif %}
{% endwith %}
{% endwith %}
Since I'm a very beginner with Django and Python, I'm pretty sure this approach is far worse than actually creating a custom helper! So I'm not suggesting anyone should be using this. This was just my attempt on trying to solve this with the available template helpers and without any custom stuff.
Hope this helps
Lo primero es multiplicar por -1 para convertirlo en una valor negativo y guardarlo en una variable y posterior a usar la suma
The first thing is to multiply by -1 to turn it into a negative value
and save it in a variable and then use the add
{% widthratio val2 1 -1 as result %}
{{result|add:val1}}
After search I found that I can make {% with var=value %} with filters to make the arithmetic operations "with other variables or not"
For example: I have x = 5 and y = 3 and need to add the y's value to x value, all what I need is these steps:
1- Create variable x : {% with x=5 %}
2- Create variable y : {% with y=3 %}
3- In my HTML tags, say <h1>, write that : <h1>{{ x|add:y }}</h1>
4- Close the y's with : {% endwith %}
5- Close the x's with : {% endwith %}
Hope it works with you, it worked with me.
{% with i=3 %}
{% with x=1 %}
<h1>{{i|add:x}}</h1> <!-- result is 4 -->
{% endwith %}
{% endwith %}
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.
Django templates offer the builtin tag cycle for alternating between several values at different points in a template (or for loop in a template) but this tag does not reset when it is accessed in a scope outside of the cycles definition. I.e., if you have two or more lists in your template, the rows of all of which you'd like to use some css definitions odd and even, the first row of a list will pick up where the last left off, not with a fresh iteration from the choices (odd and even)
E.g., in the following code, if the first blog has an odd number of entries, then the first entry in a second blog will start as even, when I want it to start at odd.
{% for blog in blogs %}
{% for entry in blog.entries %}
<div class="{% cycle 'odd' 'even' %}" id="{{entry.id}}">
{{entry.text}}
</div>
{% endfor %}
{% endfor %}
I've tried obviating this by patching with the resetcycle tag offered here:
Django ticket: Cycle tag should reset after it steps out of scope
to no avail. (The code didn't work for me.)
I've also tried moving my inner loop into a custom tag, but this also did not work, perhaps because the compile/render cycle moves the loop back into the outer loop? (Regardless of why, it didn't work for me.)
How can I accomplish this simple task!? I'd prefer not to create a data structure in my view with this information pre-compiled; that seems unnecessary. Thanks in advance.
The easiest workaround (until the resetcycle patch gets fixed up and applied) is to use the built-in "divisibleby" filter with forloop.counter:
{% for entry in blog.entries %}
<div class="{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}" id="{{ entry.id }}">
{{ entry.text }}
</div>
{% endfor %}
A little more verbose, but not hard to understand and it works great.
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#cycle
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Give up and use Jinja2 Template System
I gave up on django template language, it's very restricted in what you can do with it.
Jinja2 uses the same syntax that the django template uses, but adds many enhancements over it.
EDIT/NOTE ( I know it sounds like a big switch for just a minor issue, but in reality I bet you always find yourself fighting the default template system in django, so it really is worthwhile and I believe it will make you more productive in the long run. )
You can read this article written by its author, although it's technical, he mentions the problem of the {% cycle %} tag in django.
Jinja doesn't have a cycle tag, it has a cycle method on the loop:
{% for user in users %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>
{% endfor %}
A major advantage of Jinja2 is that it allows you to use logic for the presentation, so if you have a list of pictures, you can put them in a table, because you can start a new row inside a table every N elements, see, you can do for example:
{% if loop.index is divisibleby(5) %}
</tr>
{% if not loop.last %}
<tr>
{% endif %}
{% endif %}
you can also use mathematical expressions:
{% if x > 10 %}
and you can access your python functions directly (but some setup is required to specify which functions should be exposed for the template)
{% for item in normal_python_function_that_returns_a_query_or_a_list() %}
even set variables ..
{% set variable_name = function_that_returns_an_object_or_something() %}
You can use tagged cycle and resetcycle (new in Django 1.11) calls (from https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std:templatetag-resetcycle ):
{% for blog in blogs %}
{% cycle 'odd' 'even' as rowcolors silent %}
{% resetcycle rowcolors %}
{% for entry in blog.entries %}
{% cycle rowcolors %}
<div class="{{ rowcolors }}" id="{{entry.id}}">
{{ entry.text }}
</div>
{% endfor %}
{% endfor %}
I end up doing so, with the forloop.counter0 - It works great!
{% for product in products %}
{% if forloop.counter0|divisibleby:4 %}<div class="clear"></div>{% endif %}
<div class="product {% if forloop.counter0|divisibleby:4 %}col{% else %}col20{% endif %}">
Lorem Ipsum is simply dummy text
</div>
{% endfor %}
The easiest answer might be: "give up and use jQuery." If that's acceptable it's probably easier than fighting with Django's templates over something so simple.
There's a way to do it server-side with an iterator that doesn't keep a simultaneous copy of all the entries:
import itertools
return render_to_response('template.html',
{
"flattened_entries": itertools.chain(*(blog.entries for blog in blogs)),
})