Django模板:在标签中包含段落的前n个单词

时间:2010-01-14 10:54:55

标签: django templates django-templates

使用标准的Django模板系统,是否有任何片段/可重复使用的模板标签可以将一段文本中的前n个单词包装在标签中,以便我可以设置样式?

我理想的是:

{{item.description|wrap:"3 span big"}}

输出:

<span class="big">Lorem ipsum dolor</span> sit amet, consectetur adipiscing elit.

如果由于任何原因,这不可行或者很难获得,我可以使用JavaScript并在客户端执行,但我希望能够在页面输出上执行此操作。

3 个答案:

答案 0 :(得分:5)

老实说,我没有对此进行测试,但我想它应该可行:

{% with item.description.split as desc %}
    <span class="big">{{ desc|slice:":3"|join:" " }}</span> 
    {{ desc|slice:"3:"|join:" " }} 
{% endwith %}

更新:现在可以使用

答案 1 :(得分:2)

事实证明,编写过滤器非常简单(并且完全符合预期的方式) 这可以做得更安全,但做的工作(除非有人将html作为参数传递,否则不会破坏):

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter(name='wrap')
@stringfilter
def wrap(value, arg):
    params = arg.split()
    n = int(params[0])
    tag = params[1]
    tagclass = params[2]
    words = value.split()
    head = ' '.join( words[:n] )
    tail = ' '.join( words[n:] )
    return mark_safe('<%s class="%s">%s</%s> %s' % (tag, tagclass, head, tag, tail))

答案 2 :(得分:1)

在视图函数中拆分第一个 n 单词有什么问题?

words = text.split()
head = ' '.join( words[:3] )
tail = ' '.join( words[3:] )

您向模板提供headtail以进行呈现。

毕竟,这就是视图功能的用途。

相关问题