Django slice string in template

index.html

<td>{% if place or other_place or place_description%}{{ place}} {{ other_place}} {{place_description}}</td> 

This displays all the data in the template. I want to truncate a string if it is greater than 80.

Conditions, 1. If a place variable has more than 80 characters, it must trim them and not show two other variables, such as other_place and place_description.

2. If the variable place and variable_place has a value of more than 80 characters, in this case it should be truncated from place_variable, you do not need to specify the variable place_description.

3. If all three are theirs and the 80th character is made from place_description, you must truncate them.

All fields are optional, so any field appears for display, it should contain only 80 characters.

Need help for this.

thanks

+4
source share
2 answers

You can 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 higher,

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 %} 
+9
source

Perhaps you can do this with a combination of add / truncatechars, for example.

 {{ place|add:other_place|add:place_description|truncatechars:80}} 
+3
source

Source: https://habr.com/ru/post/1490922/


All Articles