How to use javascript variable in django if statement (template)? - javascript

I'm trying to update my html element with django if statement:
element.innerHTML= `{% if person.name == ${value} %} something {% endif %}`
but I receive an error:
TemplateSyntaxError at /
Could not parse the remainder: '${value}' from '${value}'
I also tried:
`{% if person.name == ${value} %} something {% endif %}`
But the statement doesn't work properly.
Is there anything I can do to combine javascript with Django variables?

Short Answer
No. You can not do this, at least not that easily.
Detailed (slightly) Answer
Django replaces all tags, {{ }} and {% %} with the result at the server (back end) end when the page is rendered, before it gets to the client. Your JavaScript (JQuery?) variable is evaluated by the client (the front end). Django will not know what ${value} is. So, no, you can not use a JavaScript variable in Django template code.
This does not mean you can not achieve what you want, but it must be done in the following way. Your JavaScript code can fetch the value of person.name from a view and then you can do your if statement in the JavaScript file after the response from the fetch is received. The view could return the value of person.name as a JsonResponse

Related

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 %}
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.
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

Passing a session to a Django template via jQuery

I'm trying to $.load() a Django template that uses {% if user.is_authenticated %}. Unfortunately, the user object is undefined in the template when rendered on the server only if it's in response to an AJAX-generated HTTP request.
my_template.html:
{% if user.is_authenticated %}
<div>This should be printed</div>
{% else %}
<div>But this is because there is no user object</div>
{% endif %}
my_loader.html:
{% if user.is_authenticated %}
<div>This works fine because I'm logged in</div>
{% endif %}
<div id="template'></div>
<script>
$('#template').load('/my_template.html');
</script>
views.py (using django-annoying's #render_to decorator):
#render_to('my_template.html')
def my_template(request):
return {}
The problem, as I understand it, is that the "context" available in the rendering of my_loader.html is not made available to the server through .load(). I don't know whether this "context" is a session, a cookie, or something in the header, but the result is that when the server renders my_template.html from an HTTP request generated through AJAX, there is no user object. When I load it organically in the browser it works fine.
If it helps:
This is on the same domain.
I've already tried using .ajax() instead with xhrFields: { withCredentials: true }
I've already tried using .ajax() instead with headers: { 'sessionid': $.cookie('sessionid') }. The sessionid cookie did not exist (although csrftoken did, so I know I was looking in the right place).
Any idea how to make the user object from my_loader.html available to the server when it loads pages like my_template.html via AJAX?
I assume you expected {% if user.is_authenticated %} to be evaluated on Javascript side? Well, it's not how this works. Javascript has no idea of what's on the server side, and how to parse, evaluate or bind the user template variable.
In order for $('#template').load('/my_template.html'); to work, you have to make sure that my_template.html gets rendered by Django before it's returned.
Just create a view (in Django) to render my_template.html. Don't worry about the session - it should work because along with your ajax request, cookies (which identify session) are sent as well, so Django can pick the right session, and pull user object from it.
So I feel bad because there's actually nothing wrong with my example code--in my attempts to distill the complex actual code down to an abstract level to present it to you all, I inadvertently left out a complexity that was the root cause of my problem.
Turns out WTK's and my original intuition that the cookie would be passed in the .load() request by default was, in fact, correct (inspecting the HTTP requests confirms).
So the real issue is that actually, I didn't have one template but two nested, and the latter one was actually a template tag. So the real structure was more like:
my_template.html:
Some stuff
{% my_template_tag %}
my_template_tag.html:
{% if user.is_authenticated %}
<div>This should be printed</div>
{% else %}
<div>But this is because there is no user object</div>
{% endif %}
tags.py
#register.inclusion_tag('my_template_tag.html')
def my_template_tag():
return {}
... where views.py and my_loader.html are the same as presented above. In retrospect, I should've noticed that the my_template_tag() did not take a request param, which means that it wouldn't be in the RequestContext to make user available. Basically: template tags don't implicitly have the request in their contexts as templates do, and since the user just comes from request.user it is also not available.
For those who may later read this, there are two solutions:
Pass the user object manually in as a parameter to the template_tag.
Use {% include %} with the with keyword, if possible, as it passes the request by default.
Thanks, still, for all your help rubber-ducking this! I couldn't have figured out the real problem without you guys forcing me to go back and question my original assumptions!

Sending JSON data as context quotes becoming "?

I am trying to send some schedule data to a webpage using Django and JSON format. My view to send this data looks like this:
def sessionscheduler(request):
c = connection.cursor()
c.execute("SELECT * FROM meter_schedule WHERE id = 1")
scheduleArray = []
for row in c.fetchall():
data = dict([('lastUpdate',row[1]), ('weekdaysOn',row[2]), ('weekdayChargeRateOffPeriodKwh',row[3]), ('weekdayEveningChargeOn',row[4]), ('weekdayEveningStart',row[5]),
('weekdayEveningDuration',row[6]), ('weekdayDayChargeOn',row[7]), ('weekdayDayStart',row[8]), ('weekdayDayDuration',row[9]), ('weekendsOn',row[10]),
('weekendChargeRateOffPeriodKWh',row[11]), ('weekendEveningChargeOn',row[12]), ('weekendEveningStart',row[13]), ('weekendEveningDuration',row[14]),
('weekendDayChargeOn',row[15]), ('weekendDayStart',row[16]), ('weekendDayDuration',row[17])])
scheduleArray.append(data)
jscheduleArray = json.dumps(scheduleArray)
context = {'jscheduleArray' : jscheduleArray}
return render(request, 'sessionscheduler.html', context)
I have used a template to render what is in jscheduleArray and it is coming out exactly how I want on the HTML page. However I want to use this data in my JavaSript file. The problem is that the quotes are not "" in the page source they are " which the script does not like. How do I fix this. Also I have a separte js file, is there anyway to directly call the JSON object into the the .js file? I am using YUI and pure JS.
I think you can use autoescape tag in your template to not escape the quotes
# sessionscheduler.html
{% autoescape off %}
{{ your_string }}
{% endautoescape %}

How to pass a list from Python, by Jinja2 to JavaScript

Let's say I have a Python variable:
list_of_items = ['1','2','3','4','5']
and I pass it to Jinja by rendering HTML, and I also have a function in JavaScript called somefunction(variable). I am trying to pass each item of list_of_items. I tried something like this:
{% for item in list_of_items %}
<span onclick="somefunction({{item}})">{{item}}</span><br>
{% endfor %}
Is it possible to pass a list from Python to JavaScript or should I pass each item from list one by one in a loop? How can I do this?
To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe Jinja filter, to prevent your data from being htmlescaped.
You can achieve this by doing something like that:
The view
import json
#app.route('/')
def my_view():
data = [1, 'foo']
return render_template('index.html', data=json.dumps(data))
The template
<script type="text/javascript">
function test_func(data) {
console.log(data);
}
test_func({{ data|safe }})
</script>
Edit - exact answer
So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:
The view
import json
#app.route('/')
def my_view():
data = [1, "foo"]
return render_template('index.html', data=map(json.dumps, data))
The template
{% for item in data %}
<span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}
Edit 2
In my example, I use Flask, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.
Edit 3 (Security warning)
NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!
Otherwise, you would expose your application to XSS vulnerabilities!
I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c'] with render_template('show_entries.html', letters=letters), and set
var letters = {{ letters|safe }}
in my javascript code. Jinja2 replaced {{ letters }} with ['a','b','c'], which javascript interpreted as an array of strings.
You can do this with Jinja's tojson filter, which
Dumps a structure to JSON so that it’s safe to use in <script> tags [and] in any place in HTML with the notable exception of double quoted attributes.
For example, in your Python, write:
some_template.render(list_of_items=list_of_items)
... or, in the context of a Flask endpoint:
return render_template('your_template.html', list_of_items=list_of_items)
Then in your template, write this:
{% for item in list_of_items %}
<span onclick='somefunction({{item | tojson}})'>{{item}}</span><br>
{% endfor %}
(Note that the onclick attribute is single-quoted. This is necessary since |tojson escapes ' characters but not " characters in its output, meaning that it can be safely used in single-quoted HTML attributes but not double-quoted ones.)
Or, to use list_of_items in an inline script instead of an HTML attribute, write this:
<script>
const jsArrayOfItems = {{list_of_items | tojson}};
// ... do something with jsArrayOfItems in JavaScript ...
</script>
DON'T use json.dumps to JSON-encode variables in your Python code and pass the resulting JSON text to your template. This will produce incorrect output for some string values, and will expose you to XSS if you're trying to encode user-provided values. This is because Python's built-in json.dumps doesn't escape characters like < and > (which need escaping to safely template values into inline <script>s, as noted at https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements) or single quotes (which need escaping to safely template values into single-quoted HTML attributes).
If you're using Flask, note that Flask injects a custom tojson filter instead of using Jinja's version. However, everything written above still applies. The two versions behave almost identically; Flask's just allows for some app-specific configuration that isn't available in Jinja's version.
To add up on the selected answer, I have been testing a new option that is working too using jinja2 and flask:
#app.route('/')
def my_view():
data = [1, 2, 3, 4, 5]
return render_template('index.html', data=data)
The template:
<script>
console.log( {{ data | tojson }} )
</script>
the output of the rendered template:
<script>
console.log( [1, 2, 3, 4] )
</script>
The safe could be added but as well like {{ data | tojson | safe }} to avoid html escape but it is working without too.
I can suggest you a javascript oriented approach which makes it easy to work with javascript files in your project.
Create a javascript section in your jinja template file and place all variables you want to use in your javascript files in a window object:
Start.html
...
{% block scripts %}
<script type="text/javascript">
window.appConfig = {
debug: {% if env == 'development' %}true{% else %}false{% endif %},
facebook_app_id: {{ facebook_app_id }},
accountkit_api_version: '{{ accountkit_api_version }}',
csrf_token: '{{ csrf_token }}'
}
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}
Jinja will replace values and our appConfig object will be reachable from our other script files:
App.js
var AccountKit_OnInteractive = function(){
AccountKit.init({
appId: appConfig.facebook_app_id,
debug: appConfig.debug,
state: appConfig.csrf_token,
version: appConfig.accountkit_api_version
})
}
I have seperated javascript code from html documents with this way which is easier to manage and seo friendly.
you can do it
<tbody>
{% for proxy in proxys %}
<tr>
<td id={{proxy.ip}}>{{proxy.ip}}</td>
<td id={{proxy.port}}>{{proxy.port}}</td>
<td>{{proxy.protocol}}</td>
<td>{{proxy.speed}}</td>
<td>{{proxy.type}}</td>
<td>{{proxy.city}}</td>
<td>{{proxy.verify_time}}</td>
<td>
<button type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-paste" aria-hidden="true" onclick="copyProxy('{{proxy.ip}}', '{{proxy.port}}')"></span>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
Make some invisible HTML tags like <label>, <p>, <input> etc. and name its id, and the class name is a pattern so that you can retrieve it later.
Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.
{% for i in range(maintenance_next|length): %}
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>
{% endfor%}
Now you can retrieve the data in javascript using some javascript operation like below -
<script>
var total_len = {{ total_len }};
for (var i = 0; i < total_len; i++) {
var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");
var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");
//Do what you need to do with tm1 and tm2.
console.log(tm1);
console.log(tm2);
}
</script>

javascript-readable json from python

My view computes a json and outputs a json.dumps(), and I'm passing this as the dictionary key data. I'm trying to pass this to a script element in my template, but when rendering, the browser gets it as a python-escaped string{"nodes": [{"count":...... which isn't readable to the javascript. What I need is python to send it as a JS-escaped string, something like this {"nodes": [{"count":.......
I tried str(data) and eval(data) without success. Basically I need python to send the string just as if it were printing it to the console. Thanks
If I understand well, you want to use a json in a template.
In order to do that, you have to disable the escaping, for exemple like this.
{% autoescape off %}
var x={{json_var}}
{% endautoescape %}
Note that instead of using
{% autoescape off %}
{{ my_json }}
{% endautoescape %}
You can simply use a filter :
{{ my_json|safe }}
This works for me:
return HttpResponse(json.dumps({'foo' : 'bar'}, ensure_ascii=False),
mimetype='application/json')

Categories

Resources