django模版中的截断过滤器

django模版中的截断过滤器

想输出一段摘要,需要用到截断过滤器,查阅了官方文档发现truncatewords方法

但是这个方法只能按照词【空格】 来截断需要的内容。不能按照字符长度截断。官方竟然没有提供相关的功能。

 

For example: 
{{ value|truncatewords:2 }}
 If value is "Joel is a slug", the output will be "Joel is ...". Newlines within the string will be removed. 
{{ value|truncatewords_html:2 }} 
If value is "<p>Joel is a slug</p>", the output will be "<p>Joel is ...</p>". 

谷歌一下后发现stackoverflow上有解决办法。下面是一个取巧的办法。


{{ value|slice:"5" }}{% if value|length > 5 %}...{% endif %} 

一行代码就搞定了。很方便。另外一个办法就是创建一个自定义的template filter

 

from django import template
register = template.Library() 
@register.filter("truncate_chars") 
def truncate_chars(value, max_length): 
  if len(value) > max_length: 
    truncd_val = value[:max_length] 
    if not len(value) == max_length+1 and value[max_length+1] != " ":
      truncd_val = truncd_val[:truncd_val.rfind(" ")] 
    return truncd_val + "..." 
  return value 


posted @ 2011-11-23 20:53  LemonLi  阅读(1047)  评论(0编辑  收藏  举报