python - 如何在 django 模板中使用 for 函数?

标签 python django django-models django-templates

我正在使用此函数来标记我的博客文章中的句子:

def sentence_tokenize(string):
    sents2 = sent_tokenize(string)
    return sents2

在我的 html 模板中,当我使用这行代码时:

 {% sentence_tokenize post.text %}

它成功地将帖子文本发送到函数并返回所有句子的列表。

我需要使用for循环将每个句子放在单独的行中,但它给出了一个错误,这是我的代码:

{% for sentence in sentence_tokenize post.text %}
    {{ sentence }}
{% endfor %}

这是错误:

TemplateSyntaxError at /post/1/ 'for' statements should use the format 'for x in y': for sentence in sentence_tokenize post.text

有什么建议吗?

最佳答案

您可以通过使用“as”将句子 token 化的结果分配给变量来完成此操作,如下所示:

{% sentence_tokenize post.text as sentences %}

然后像这样迭代句子:

{% for sentence in sentences %}
    {{ sentence }}
{% endfor %}

关于python - 如何在 django 模板中使用 for 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858321/

相关文章:

python - 尝试使用 BeautifulSoup 打印表格的单行,但行位置不断变化

python - matplotlib 补丁集合中的 Zorder 规范?

python - 使用 Python 将 NetCDF 文件转换为 CSV 或文本

python - 安全优化文件权限django+apache+mod_wsgi

javascript - 上传多个文件并显示进度条

python - 模型保存方法。保存前调整图像大小

python - 如何在 django 中获取外键的特定字段?

python - set_cookie() 缺少 1 个必需的位置参数 : 'self'

python - Django get_profile() 方法不适用于扩展用户模型

python - Django : What is the role of ModelState?