我正在用 Django 构建一个博客应用程序,当我显示所有博客时,我想显示每个条目的一小段博客摘录。谁能告诉我该怎么做?
One way to do that would be to make an extra field and store a fixed number of words for each blog entry, let's say 20 words. But then that would be storing redundant information in the database. Is there a better way to do that?
最佳答案
我建议您使用 truncatewords模板过滤器。
模板示例:
<ul>
{% for blogpost in blogposts %}
<li><b>{{blogpost.title}}</b>: {{blogpost.content|truncatewords:10}}</li>
{% endfor %}
</ul>
如果博客内容存储为 HTML,请使用 truncatewords_html
确保打开的标签在截断点之后关闭(或与 striptags
结合以删除 html 标签)。
如果你想截断字符(而不是单词),你可以使用slice
:
{{blogpost.content|slice:":10"}}
(输出前 10 个字符)。
如果内容存储为 HTML,请结合 striptags
以避免打开标签问题:{{blogpost.content|striptags|slice:":10"}}
关于python - Django 中的博客摘录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7894618/