Django:如何获取“truncatewords”的截断部分 [英] Django: How to get the truncated portion of "truncatewords"
问题描述
我试图在Django中将一个段落分成两半,这样我就可以应用不同的样式,但是无法弄清楚如何获得截断的后半部分。
为了得到上半部分我使用:
< ; p class =leader> {{post.body | truncatewords:30}}< / p>
下半部分会像
< p> {{post.body | truncatewords ?? }}< / p为H. <! - 需要得到30 - 结束 - >
我确定有一个简单的方法 - 让我知道是否有人知道如何做到这一点。
谢谢!
)
from django import template
<
register = template.Library()
@ register.filter
def truncatedwords(value,arg):
return.join(value.split()[arg:])
def truncatedwords(value,arg):
... return.join(value.split()[arg:])
...
>>> value =这是第二部分
>>> arg = 3
>>> truncatedwords(value,arg)
'second part'
>>>
您需要知道的是文档: https://docs.djangoproject.com/en/1.6/howto/custom-template-tags/
更新:
看看Django的源代码。 Truncatewords生活在:
django.template.defaultfilters
并使用 django.utils.text.Truncator
I'm trying to split a paragraph in half in Django so that I can apply different styling, but can't figure out how to get the second half of the truncation.
To get the first half I'm using:
<p class="leader">{{ post.body|truncatewords:30 }}</p>
The second half will be something like
<p>{{ post.body|truncatewords?? }}</p> <!-- need to get 30 - end -->
I'm sure there's an easy way - Let me know if anyone knows how to do this.
Thanks!
It is easy, ask on SO :)
from django import template
register = template.Library()
@register.filter
def truncatedwords(value, arg):
return " ".join(value.split()[arg:])
Quick test:
>>> def truncatedwords(value, arg):
... return " ".join(value.split()[arg:])
...
>>> value = "This is the second part"
>>> arg = 3
>>> truncatedwords(value, arg)
'second part'
>>>
All you need to know is in the docs: https://docs.djangoproject.com/en/1.6/howto/custom-template-tags/
UPDATE:
Take a look at Django source. Truncatewords lives at:
django.template.defaultfilters
and uses django.utils.text.Truncator
这篇关于Django:如何获取“truncatewords”的截断部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!