I am spitting out some values with a for loop and want to make sure that it only displays X characters. I'm relatively new to Django.
For example:
<div class="bookauthor">
by
{% for author in book.volumeInfo.authors %}
{% if not forloop.first %}&{% endif %}
{{author}}
{% endfor %}
</div>
Would produce a list of book authors, e.g.:
by Lennart Berggren & Jonathan M. Borwein & Peter B. Borwein
and I'd only like 30 characters, since sometimes the list of authors can be long.
I understand that I can use truncatechars (new in Django 1.4) to do this on a single value like {{author|truncatechars:9}}
, but I'm wondering if there is an elegant way to apply to the for loop, or the resulting text from the for loop. Please let me know if this isn't clear.
EDIT
truncatechars does not seem to work properly when used in a {% filter %}. All it produces is "...". I'll test some more, could be a bug. truncatewords works well, and I may be more suitable for this situation anyhow.
<div class="bookauthor">
by
{% filter truncatechars:30 %}
{% for author in book.volumeInfo.authors %}
{% if not forloop.first %}&{% endif %}
{{author}}
{% endfor %}
{% endfilter %}
</div>