如何发现内容被截断?
我正在尝试构建一个博客应用程序,问题是当我在模板中使用标签“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 %}
I'm trying to build a blog app and the problem is when I use tag 'truncatewords_html' in my template to truncate posts longer than specified number of words, I need to link to complete post by some title like 'read more...' after truncation. So I should know that the post was truncated or not.
P.S.: Is this a pythonic way to solve the problem?
{% 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 %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这相当复杂,但 django 有一些奇怪的角落。基本上我认为如果在 x 和 x+1 个单词处截断字符串长度是否相同,则字符串尚未被截断...
This is pretty convoluted but django has some weird corners. Basically I figure if the string length is the same if you truncate at x and x+1 words then the string has not been truncated...
您可以编写自定义模板标签(请参阅 django 文档 ),或者通过
length
内置过滤器。You could write a custom template tag (see django docs), or manually check in the template, whether the content you want to display exceeds the given length via
length
builtin filter.这取决于个人喜好,但就我的口味而言,您在模板中做了太多工作。我会在 Post 模型上创建一个方法,也许是
read_more_needed()
,它根据文本的长度返回 True 或 False。例如:那么你的模板将是:
It comes down to personal preference, but for my taste you're doing way too much work in the template. I would create a method on the Post model,
read_more_needed()
perhaps, which returns True or False depending on the length of the text. eg:Then your template would read:
查看 http://code.djangoproject.com/ticket/6799
这个补丁提供了一种方法替换截断文本的默认省略号。
Check out http://code.djangoproject.com/ticket/6799
This patch provides a method to replace the default elipses for truncated text.