Reputation: 691
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 %}
Upvotes: 2
Views: 4919
Reputation: 23
As Jinja2 variables are parsed on the server side, you can't do this directly.
Assuming you are using the Python Flask framework, this workaround (or an adaptation of it) may serve your purpose:
In your script, set the value of a HTML form to the desired value:
document.getElementById('response').value = JSON.parse(req.responseText);
In your HTML, the form will take the desired value:
<input type = "hidden" id = "response" name="response" value = '0' style="width: 8em;">
When the form is posted, in your Python code, you capture the request into a variable:
session['response'] = int(request.form['response'])
When you render the template, you can use the variable in Jinja2:
{% set myFiles = session['response'] %}
Upvotes: 0
Reputation: 1
I think you looking for including expression or statement in js. It's possible, use double quotes(" "). One thing you can't directly add in the js file. use your code at the end of the code
var response = JSON.parse(req.responseText);
"{% set myFiles = response.fileList %}"
For Clear Understanding,
app.py
@app.route('/')
def home():
return render_template('index.html',check=0,text='hai')
index.html
<div>
.
.
.
</div>
<script>
var text = {{ text }} //Throws error
var text = "{{ text }}" //console it
{% if(check == 0) %}
console.log('its true')
{% endif %} //Throw error
"{% if(check == 0) %}"
console.log('its true')
"{% endif %}"//Success
</script>
It's working for me. vote if works
Upvotes: 0
Reputation: 5589
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.
Upvotes: 2