I'm trying to render this simple code on a jinja 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 on the HTML template for example like this:
<h1>{{item}}</h1>
it shows this on the code:
<h1><script></h1>
is there anyway to decode that variable to show as it is declared?
CodePudding user response:
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.
CodePudding user response:
Just found out how to do it,
adding in the HTML:
{% autoescape false %}
{{ your_variable }}
{% endautoescape %}