Search code examples
javascriptpythonhtmlchart.jsjinja2

Jinja convert chat.js charts to images when rendering template


I have a question about javascript within Jinja2 before I start on my project, so I can understand if jinja is the right solution to use

  • I want to create an html email template that will fill in some values for each user, and then send them the rendered template via email. I already have the email functionality set up

  • I want to include some charts from chart.js on the page, but because JS isn't allowed on emails I have to convert the charts to images before sending the email.

My question is, does jinja allow for this to happen when rendering the template? Can I make sure that the charts are converted to images when the template is rendered, and all JS is removed/inactive before sending the template?


Solution

  • No, Jinja (or any similar template system) cannot convert JavaScript charts to images on the backend, because JavaScript runs in a browser, so you need a headless browser engine (or similar JS runtime) on the backend for the conversion. It's doable, but it will make your environment more complicated since you'll need to maintain a JS runtime as well along with the Python environment. If you want to go in this direction, have a look at chartjs-node-canvas that uses NodeJS to export a chart, or any headless browser.

    However I highly recommend a different way: use a Python plotting library like Matplotlib. In an email you cannot even use any JS interactivity anyways, so a static plotting library is perfect for this task. Furthermore it's Python, so no need to add a different runtime to your environment.