我有一个功能可以自动将问题 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/