简体   繁体   中英

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

I have a function to automatically replace issue IDs to links:

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)

Then {{text}} is passed to template.

It works, but there is a side effect - all kind of html is unescaped in text after this. Is there any way to avoid html escaping only for the link?

use the safe filter on text. it would look like this in the template,

{{ text |safe }}

safe will state that the html found in this text is safe to render and as such doesn't have to be escaped.

the flask page on templates briefly talks about the safe filter around half way down the tutorial. The safe filter just says that everything in this text is safe and turns off html escaping.

That's the workaroung I found during this night:

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

Could you please explain how could I do the same thing using this "safe" feature?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM