使用标准的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))更多推荐
发布评论