【问题标题】:How to find that the content is truncated?如何发现内容被截断?
【发布时间】:2009-11-26 09:41:12
【问题描述】:

我正在尝试构建一个博客应用程序,问题是当我在模板中使用标签“truncatewords_html”来截断长于指定字数的帖子时,我需要通过一些标题链接以完成帖子,例如“阅读更多” ...' 截断后。所以我应该知道帖子是否被截断。

P.S.:这是解决问题的pythonic方法吗?

{% ifequal post.body|length post.body|truncatewords_html:max_words|length %}
  {{ post.body|safe }}
{% else %}
  {{ post.body|truncatewords_html:max_words|safe }}<a href="{{ post.url}}">read more</a>
{% endifequal %}

【问题讨论】:

    标签: django truncate


    【解决方案1】:

    这很复杂,但 django 有一些奇怪的角落。基本上我想如果你在 x 和 x+1 个单词处截断字符串长度是否相同,那么字符串没有被截断......

    {% ifnotequal post.body|truncatewords_html:30|length post.body|truncatewords_html:31|length %}
       <a href="#">read more...</a>
    {% endifnotequal %}
    

    【讨论】:

      【解决方案2】:

      您可以编写自定义模板标签(参见django docs),或者通过length 内置过滤器手动检查模板中要显示的内容是否超过给定长度。

      【讨论】:

      • +1 为检查显示是否超过长度的简单方法。简单,工作正常。
      【解决方案3】:

      这取决于个人喜好,但根据我的口味,您在模板中做的工作太多了。我会在 Post 模型上创建一个方法,read_more_needed() 可能会根据文本的长度返回 True 或 False。例如:

      def read_more_needed(self):
          from django.utils.text import truncate_html_words
          return not truncate_html_words(self.body,30)==truncate_html_words(self.body,31)
      

      然后您的模板将显示为:

      {% if post.read_more_needed %}
        {{ post.body|truncatewords_html:30|safe }}<a href="{{ post.url}}">read more</a>
      {% else %}
        {{ post.body|safe }}
      {% endif %}
      

      【讨论】:

      • 如果您要在模型中添加“read_more_need()”,那么您也应该在模型中进行截断。执行截断的相同代码应确定内容是否已被截断。
      【解决方案4】:

      查看http://code.djangoproject.com/ticket/6799

      此补丁提供了一种替换截断文本的默认省略号的方法。

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 2014-05-22
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        相关资源
        最近更新 更多