truncatewords_html Filter

String Most Useful

Argument: n (required) – number of words to truncate to.

Documentation

Truncates a value to n words and appends an ellipsis (…). It does not count HTML tags as words and closes any tags that were left open as a result of the truncation.

Variable

blurb = '<p>You are <em>pretty</em> smart!</p>'

Template

{{ blurb|truncatewords_html:3 }}

Result

<p>You are <em>pretty…</em></p>

Autoescaping

Be aware that autoescaping is on by default in Django. If you do not turn it off, either with the {% autoescape off %} tag or the safe filter, the HTML will be escaped.

The easiest way to avoid this is to chain on the safe filter:

{{ blurb|truncatewords_html:3|safe }}

Commentary


Did we get something wrong? Is there a use case for the truncatewords_html filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on April 14, 2020, 9:53 a.m. EST