'FastAPI - How to render Jinja2 template with variable that contains special characters?

I'm trying to render this Jinja2 template:

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request, item: Optional[str] = None):
    item = "<script>"
    return templates.TemplateResponse('index.html', {
     'request': request,
     'item': item
    })

but when I use the variable in the HTML template, for example:

<h1>{{item}}</h1>

it shows this in the code:

<h1>&lt;script&gt;</h1>

is there anyway to decode that variable to show as it is declared?



Solution 1:[1]

FastAPI uses the templating support in starlette, which sets the Jinja2 autoescape option by default.

You can disable that like this:

templates = Jinja2Templates(directory="templates")
templates.env.autoescape = False

With more recent versions of starlette, you may also be able to do this:

templates = Jinja2Templates(directory="templates", autoescape=False)

...but with the version I'm running the latter option fails. The former option should work in any case.

Solution 2:[2]

Just found out how to do it,

adding in the HTML:

{% autoescape false %}
{{ your_variable }}
{% endautoescape %}

Solution 3:[3]

Another way is to wrap the markup you consider safe to render in markupsafe.Markup.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks
Solution 2 Ronyerba
Solution 3 auxsvr