I know we can set Jinja variable to js variable like this.
var x = {{ \'value\' }}
but I am trying to do the reverse. i.e I am trying to s
The way you're describing, it can't be done.
Let's review Python, Jinja2, and JavaScript, because I think we can still achieve what you want.
Python is the language of your server, which will create the HTML sent to your clients.
Jinja2 is a templating engine for Python, which makes it easy to generate HTML without writing it directly. Notice that you're calling a function like render_template()
in your backend. This generates the HTML using Jinja2 syntax, replacing Jinja2 statements with values known to the server, and inserting them into the HTML before it gets presented to the client. Think of Jinja2 as shorthand for variable insertion and simple scripting for making HTML.
JavaScript is your frontend scripting language, running on the client's browser once the HTML has been generated and served.
The reason you can't use Javascript to "set a Jinja2 variable" is because there are no Jinja2 variables in the rendered HTML sent to the client. Python and Jinja2 did that replacement on the server before sending the pure HTML/CSS/JS page to the client's browser.
Perhaps what you want to do though, is use frontend elements to change values that were initially set by python and Jinja2 on the backend. To do this, you will need to have your JavaScript send information back to the server, so the server can use this information to rerender the page, possibly inserting new values into your templates using Jinja2 in the process. Consider simply linking to a URL with the parameter you want to set.
You could link to www.yourwebsite.com?x=value
, and now x
will be set to 'value'
in the backend. You can use this in your HTML template by including {{ x }}
, which will resolve to 'value' when you call render_template()