zoukankan      html  css  js  c++  java
  • 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 


  • 相关阅读:
    redis.conf 参数说明
    BD2 catalog编目
    Altium Designer -在PCB中统一修改元器件标号的位置
    AD使用技巧-怎样绘制圆形敷铜
    运放压百率
    Altium designer 新建快捷键
    修改AD中PCB各层的透明度
    Altium Designer 使用小技巧2
    Altium Designer 使用中的小技巧1
    网络库的设计与实现
  • 原文地址:https://www.cnblogs.com/pylemon/p/2260781.html
Copyright © 2011-2022 走看看