django切片字符串在模板中 [英] django slice string in template

查看:398
本文介绍了django切片字符串在模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

index.html

 < td> {%if place或other_place或place_description%} {{place}} { {other_place}} {{place_description}}< / td> 

这是显示模板中的所有数据。如果超过长度,我想截断字符串80。



条件是
1.如果地方变量有超过80个字符,它应该截断他们,不需要显示其他两个变量,如other_place和place_description。



2.如果放置变量和other_place变量超过80个字符,在这种情况下,应该从place_variable截断不需要显示place_description变量。 p>

3.如果所有三个都是他们的,第80个字符是由place_description制作的,则需要从中删除。



所有字段不是强制性的,所以任何字段都显示,它应该只显示80个字符。



需要帮助来执行此操作。



谢谢

解决方案

您可以使用 slice -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%}


index.html

<td>{% if place or other_place or place_description%}{{ place}} {{ other_place}} {{place_description}}</td>

This is displaying all the data in template.I want to truncate the string if it is more than length 80.

Conditions are, 1.If place variable have more than 80 character,it should truncate their and need not show the other two variable like other_place and place_description.

2.If place variable and other_place variable making more than 80 character,in this case it should truncate from place_variable don't need to show place_description variable.

3.If all the three are their and the 80th character is made from place_description,need to truncate from their.

All fields are not mandatory,so whatever field is comes to display,it should show only 80 character.

Need help to do this.

Thanks

解决方案

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

这篇关于django切片字符串在模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆