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 


  • 相关阅读:
    占位 CP
    占位 LR
    占位 DL
    占位 SC
    Your name ?
    占位 RK
    Gson 关于SpringMVC和json格式问题
    JDBC
    Outlook2016 2019修改默认存储路径文件夹
    Windows Server 2016 任务管理器没有了远程控制 远程桌面,能够控制其它远程用户的会话
  • 原文地址:https://www.cnblogs.com/pylemon/p/2260781.html
Copyright © 2011-2022 走看看