Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 TemplateResponse.template.render() doesn't inject context into template

Tags:

python

jinja2

I'm using FastAPI with Jinja2.

I have a function that sends out an email. The content of the email is inside a HTML that needs to be rendered.

    async def send_confirmation_email(
        self, email: str, confirm_url: str, request: Request
    ):
        html = templates.TemplateResponse(
            "email_template.html",
            {
                "request": request,
                "header": "Thanks for joining",
                "url": confirm_url,
                "link_title": "ACTIVATE YOUR ACCOUNT",
            },
        )
        await self.send_email(
            html.template.render(),
            "Confirm Your Email",
            setting.EMAIL_SUPPORT,
            email,
        )

html.template.render() is only rendering the content of HTML without filling in the context into the placeholders. e.g. "header": "Thanks for joining" remains empty.

snippet from HTML:

<td align="center" width="120" colspan="3" valign="top"><h2>{{ header }}</h2></td>

What am I missing please?

like image 534
Houman Avatar asked Feb 26 '26 21:02

Houman


1 Answers

TemplateResponse return a starlette.responses.Response, not a renderer template .

For that, you need to use

templates.get_template("email_template.html").render({
    "request": request,
    "header": "Thanks for joining",
    "url": confirm_url,
    "link_title": "ACTIVATE YOUR ACCOUNT",
})

(ref: https://github.com/encode/starlette/blob/master/starlette/templating.py#L72)

like image 170
Cyril Jouve Avatar answered Feb 28 '26 09:02

Cyril Jouve