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 


  • 相关阅读:
    python __init__.py
    估算小结
    ssh vim中不小心按下ctrl+s
    估算方法
    SSH 下使vim语法高亮显示 && 终端下vim配置
    not enough arguments for format string搞死人
    函数的形参 实参
    Linux 共享内存机制
    select函数参数及其使用
    找出两个字符串最长公共子串
  • 原文地址:https://www.cnblogs.com/pylemon/p/2260781.html
Copyright © 2011-2022 走看看