【问题标题】:How to use for with a function in a django template?如何在 django 模板中使用函数?
【发布时间】:2017-12-05 02:44:05
【问题描述】:

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

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' 语句应使用以下格式 'for x in y': for sentence_tokenize post.text

有什么建议吗?

【问题讨论】:

    标签: python django django-models django-templates


    【解决方案1】:

    您可以通过使用 'as' 将 sentence_tokenize 的结果分配给一个变量来做到这一点,如下所示:

    {% sentence_tokenize post.text as sentences %}
    

    然后像这样遍历句子:

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

    【讨论】:

    • 谢谢。我正在寻找变量评估,但我确实知道这是与使用一样。它有效。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2014-10-12
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2016-06-26
    • 2011-01-08
    相关资源
    最近更新 更多