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 


  • 相关阅读:
    第十五篇 -- 学习第十四天打卡20190702
    第三篇 -- 方向
    第十四篇 -- 学习第十三天打卡20190701
    yum更换阿里源
    Jenkins+sonar7.3集成
    xshell 5 书写汉字乱码
    zabbix 短信报警
    zabbix 微信报警
    zabbix邮件报警
    zabbix主动监测客户端设置
  • 原文地址:https://www.cnblogs.com/pylemon/p/2260781.html
Copyright © 2011-2022 走看看