的index.html
<td>{% if place or other_place or place_description%}{{ place}} {{ other_place}} {{place_description}}</td>
这是显示模板中的所有数据。如果字符串长度超过80,我想截断字符串。
条件是, 1.如果地方变量超过80个字符,它应截断它们,不需要显示另外两个变量,如other_place和place_description。
2.如果放置变量和other_place变量超过80个字符,在这种情况下它应该从place_variable截断不需要显示place_description变量。
3.如果这三个都是他们的,而第80个字符是由place_description制作的,则需要从他们的截断中删除。
所有字段都不是必填字段,因此无论显示哪个字段,它都应该只显示80个字符。
需要帮助才能做到这一点。
由于
答案 0 :(得分:12)
您可以将slice用于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 %}
如果您使用的是django 1.4或更高版本,
您可以使用truncatechars
{% if place or other_place or place_description%}
{% with place|add:other_place|add:place_description as pl %}
{{pl|truncatechars:80}}
{% endwith %}
{% endif %}
答案 1 :(得分:3)
您可以使用add / truncatechars的组合来完成此操作,例如
{{ place|add:other_place|add:place_description|truncatechars:80}}