[Fixed]-How to truncate/slice strings on Django Template Engine?

22👍

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 %}

4👍

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

{{ place|add:other_place|add:place_description|truncatechars:80}}
👤JamesO

3👍

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’

1👍

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

👤ron_g

Leave a comment