10

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

PS:这是解决问题的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 %}
4

4 回答 4

7

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

{% ifnotequal post.body|truncatewords_html:30|length post.body|truncatewords_html:31|length %}
   <a href="#">read more...</a>
{% endifnotequal %}
于 2009-11-26T10:40:03.543 回答
2

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

于 2009-11-26T10:04:11.460 回答
1

这取决于个人喜好,但根据我的口味,您在模板中做的工作太多了。我可能会在 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 %}
于 2009-11-27T11:08:32.570 回答
0

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

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

于 2009-11-26T14:51:15.527 回答