1

I'm new to Python and Django, and have the following line of code in an html template:

{% if len(dato.titulo) > 35 %} {{dato.titulo[:35] + '...'}} {% else %} {{ dato.titulo }}{% endif %}

the {% if len(dato.titulo) > 35 %} bit throws the exception. I tried using a truncatechars filter but the django version installed is apparently old and doesn't have the filter. How could I make this work (truncate the string if it has more than 35 characters)?

4

1 回答 1

3

在 django 模板中使用|length过滤器来获取字符串的长度,因此将您的行更新为

{% if dato.titulo|length > 35 %} {{dato.titulo[:35] + '...'}} {% else %} {{ dato.titulo }}{% endif %}

看来您想截断字符串,在这种情况下您可以使用|truncatechars过滤器。因此无需检查长度并手动截断字符串。做就是了

{{ dato.titulo|truncatechars:35 }}

如果不可truncatechars用,请|slice按照@Leonardo.Z所述使用,它将截断字符串,但不会...在末尾添加。

{{ dato.titulo|slice:35 }}

或者编写您自己的模板过滤器来执行此操作。

于 2013-11-06T05:47:42.153 回答