【发布时间】:2011-11-07 19:00:43
【问题描述】:
谁能告诉我,Django 模板中是否存在 PHP 中的 substr (http://pl2.php.net/manual/en/function.substr.php) 之类的方法?
【问题讨论】:
标签: python django templates substr
谁能告诉我,Django 模板中是否存在 PHP 中的 substr (http://pl2.php.net/manual/en/function.substr.php) 之类的方法?
【问题讨论】:
标签: python django templates substr
您可以使用slice filter,但我认为没有与$length 参数等效的方法。
【讨论】:
您可以使用cut 过滤器,例如:
{{ value }} -> 'hello world'
{{ value|cut:'hello ' }} -> 'world'
【讨论】:
在python中,子字符串作为切片访问; django 中有一个内置的slice 过滤器。
【讨论】:
因为大家都觉得留下一个链接就够了,我会在这里添加一些来自django documents 的代码示例:
slice 过滤器返回列表的一部分
{{ some_list|slice:":2" }}
如果 some_list 是 ['a', 'b', 'c'],则输出将为 ['a', 'b']。
【讨论】:
参见 truncatechars,django docs 过滤器:
<p>Example {{ person.names|truncatechars:20 }}</p>
【讨论】: