Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django slice string in template

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

like image 212
user2086641 Avatar asked Jul 11 '13 14:07

user2086641


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


2 Answers

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 %}
like image 146
karthikr Avatar answered Oct 02 '22 01:10

karthikr


You could probably do it with a combination of add/truncatechars e.g.

{{ place|add:other_place|add:place_description|truncatechars:80}}
like image 24
JamesO Avatar answered Oct 01 '22 23:10

JamesO