Search code examples
javascriptpythonflaskjinja2

How to set a jinja2 expression with a Javascript variable?


How can I use a Jinja2 expression within a js function? I'd tried something similar to the lines below and the expression isn't working. The attribute fileList used in response is a list coming from flask through Json.

var response = JSON.parse(req.responseText);  
{% set myFiles = response.fileList %}

Solution

  • Jinja2 is a templating language. Meaning all template expressions will be evaluated and replaced by either text or HTML code before even served to the client. Whereas Javascript is a scripting language used on the client side.

    So there is actually no way to pass any values to a Jinja2 expression from Javascript as there simply don't exist any Jinja2 expressions on the client side because they have all been replaced already by text or html code.

    However if you simply want to pass any data from client to server there are a lot of ways to do that. Probably the most fitting for you would be an Ajax call.