python - Flask + python + jinja2 : how can I partialy replace template arguments with html code?

标签 python html flask jinja2

我有一个功能可以自动将问题 ID 替换为链接:

def addlinks(text):
    from flask import Markup
    idlist = getallissueids()
    for issueid in idlist:
        text = text.replace( issueid, "<a href=/browse/" + issueid +">" + issueid + "</a>")
    return Markup(text)

然后 {{text}} 被传递给模板。

它可以工作,但有一个副作用 - 此后所有类型的 html 在文本中都不会转义。 有什么办法可以避免仅针对链接进行 html 转义吗?

最佳答案

对文本使用安全过滤器。它在模板中看起来像这样,

{{ text |safe }}

safe 将声明此文本中找到的 html 可以安全呈现,因此不必转义。

the flask page on templates briefly talks about the safe filter around half way down the tutorial.安全过滤器只是表示此文本中的所有内容都是安全的,并关闭 html 转义。

关于python - Flask + python + jinja2 : how can I partialy replace template arguments with html code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19083104/

相关文章:

python - python 的 shutil.copyfile() 是原子的吗?

python - 将此 curl 命令转换为 Python 3

html - Bootstrap 3 - 将 4 个 div 按 25% 放置,并在下方再放置一个 div

python - Flask SQLAlchemy 连接到 MySQL 数据库

python - 如何使用 Flask 通过 HTML 表单携带带空格的字符串

python - 将值列表转换为编码变量?

python - 在raspbian上自动启动具有容错功能的python服务

javascript - 在 ng-repeat 中单独将样式应用于一个字段

html - div 没有正确排列

flask - 如何在 .kitchen.yml 中传递环境变量来测试厨房