python - Django 中的博客摘录

标签 python django blogs

我正在用 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/

相关文章:

html - Blog List Div - 解决CSS

MVC WebAPI 的 MySQL 数据库表设计

带有 Quickbooks Online API v3 的 python

Python Plotly : Percentage Axis Formatter

python - sorl-thumbnail 在 django 中不起作用

python - Django - 获取反转url所需的参数名称

python - 如何为 Cython(C++ 到 Python)实现 vector <vector <Obj>>?

python - 带有 selectfield 的 flask 链接下拉列表不是有效的选择

python - python-mysql-connector 1.16、django 1.6 和 python 3.2.3 导入错误

pagination - 使用偏移量对 Shopify 博客进行分页? (液体)