Django模板:在标签中包含段落的前n个单词(Django templating: wrap first n words of paragraph in tag)

编程入门 行业动态 更新时间:2024-10-26 10:31:24
Django模板:在标签中包含段落的前n个单词(Django templating: wrap first n words of paragraph in tag)

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

我理想的是:

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

哪个输出:

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

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

Using the standard Django templating system, is there any snippet/reusable template tag to have the first n words in a piece of text wrapped in a tag so I can style them?

What I'm ideally looking for:

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

which outputs:

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

If this would be, for any reason, not feasible or really difficult to obtain, I can use JavaScript and do it client side, but I'd like more to be able to do it on page output.

最满意答案

说实话,我没有测试这个,但我想它应该工作:

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

更新 :它现在有效

It turns out that writing a filter is really easy (and works exactly the intended way). This could be made a lot safer, but does the job (and won't break unless someone passes html as parameters):

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))

更多推荐

本文发布于:2023-07-25 10:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:段落   单词   模板   标签   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!