How to pass parameter to js function from template parameter array - javascript

I generated in tornado template table with cities and I am trying to have like last column details button
{% if globals().has_key('results') %}
{% for result in results %}
<tr>
<td>{{result['name']}}</td>
<td>{{result['citizens']}}</td>
<td style="width:100px; height:100px;">
<div class="ui-grid-b">
<a class="ui-block-a ui-icon-detail" onclick="showDetails('{{id}}',{{result['city_id']}});" data-role="ui-li-aside" data-icon="right_arrow" data-theme="a"></a>
</div>
</td>
</tr>
{% end %}
{% end %}
and on click to load on another page with parameters in url.
<script type="text/javascript">
function showDetails(id, city_id)
{
window.location = '/cities?id='+id+'&city_id='+city_id;
}
</script>
How to pass parameters to show details function ? (I cannot use ', I tried with \" but it doesn't work). Results is list of dictionaries with keys name, citizens, city_id.
{{ }} is used by tornado template to access passed parameter.

showDetails = function (id, city_id)
{
window.location = '/cities?id='+id+'&city_id='+city_id;
}
I think is the easy way

The variable inside the braces will be output directly (or, the string representation of it), so it depends what it is set to.
e.g. if you have:
id = 'foo'
results = [{ 'city_id': 'bar' }]
and you are passing them to the template, then this line:
showDetails('{{id}}',{{result['city_id']}});
will be output as follows (you can confirm this with view source):
showDetails('foo',bar);
I'm guessing you're missing the quotes around {{result['city_id']}}, unless result['city_id'] is an integer, in which case it should work. Single or double quotes are both fine in JavaScript.
However, as #Pete already pointed out, "on click to load on another page with parameters in url" is what we have the href attribute for. You can save yourself a lot of work and potential brokenness with:
<a href="/cities?id={{ id }}&city_id={{ result['city_id'] }}" ....></a>

Related

Creating custom data in Shopify to save into the customer object and access on a different page

I am trying to create custom data to save into the customer object, which I could then access on a different page. I have an input like this
<input type="hidden" id="{{ formId }}-score" name=contact[score]>
I created an exam page that uses a script to calculate the score, which is then sending the value to that input. I am trying to save that value into the customer object which I could then access on a different page like this:
{% if customer.score > 11 %} <h1> You Passed </h1> {% endif %}
In Shopify, using tags we can save custom data of the customer. You will need to add tags in the name like this: name="customer[tags]"
You can pass the value as per your need like this: value="score_11"
You can fetch the value like this: customer.tags
You can use tags in your condition.
{% if customer.tags > score_11 %}

How to set a variable (using set tag) in django template?

I want something like this inside django template. I want to use these variables in javascript file or another template file.
{% set titles = {
'table': form._meta.model._meta.verbose_name_plural.title(),
'form': form._meta.model._meta.verbose_name.title()
}
%}
{% set dtable = "dt_" + page %}
How can I create "set tag" in django template? Your answer would be helpful for me.
Although I think this is generally to be avoided (mixing template & logic is generally advised against in django), it appears this is possible through the use of the with tag.
{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}
In javascript, it would probably look like this
$(document).ready(function(){
{% with greeting="hello" %}
var text = '{{ greeting }}'
{% endwith %}
});
There are some constraints, I don't believe you can set tuples or dictionaries this way. That said, if you're trying to set more complex types using {% with ... %} that logic should probably be handled in the view.
Referenced from this SO question.
CASE 1:
If you want to access your dictionary in the HTML template. You can pass titles dictionary to the template and access any key of the dictionary by the dot (.) operator.
<div class="something1">{{ titles.table }}</div>
<div class="something2">{{ titles.form }}</div>
CASE 2:
If you want to send a dictionary to the HTML template and access in your javascript file, I would suggest you to store them in a data attribute of an input (hidden) element or any element and then access via javascript.
<input type="hidden" id="my-data-table" data-table="{{ titles }}">
You can access dictionary in your javascript file like this,
var myTitles = document.getElementById("my-data-table");
var titles = myTitles.getAttribute("data-table");

Using javascript variable in python(flask/Django) dictionary html

I am trying to use a javascript variable in a python dictionary in html, is this possible? Any help would be great.
e.g if I had a dictionary - current_data
var num_key = "4";
alert( {{ current_data[num_key] }} );
If I do the following it works perfectly,
alert( {{ current_data["4"] }} );
But with the javascript variable, it won't work.
Thanks again.
No, while you can use Jinja to create JavaScript embedded in <script> tags, you cannot use it the other way around. When Flask renders this page it's static. The page does not still have blocks of code inside {{ }} or {% %}, it holds the result of those operations. However, there are other options. You could put the contents of current_data into hidden input with the keys as the id attributes.
View
{% for key in current_data %}
<input id="{{ key }}" type="hidden" value="{{ current_data[key] }}"/>
{% endfor %}
JavaScript
var num_key = "4";
alert(document.getElementById(num_key).value);
One extra piece of advice, it's not good practice to embed JavaScript into your html. You should have a separate .js file containing this and then include it in your html.

replace parameter using jquery

I'm working with python and jinja. When I render template I sent two parameters like this :
return render_template('mod_page/index.html',
types_first = utils.questions_first(),
types_second = utils.questions_second())
questions_first and questions_second are two same functions, something like this:
def questions_first(self):
return ['Name','Surname', 'Phone']
In index page I have a tag like this:
<html lang="en">
...
I want to take lang attribute with jQuery and then to check if it is 'en' I want to use questions_first if it is 'sr' I want to use questions_second.
My question is how can I replace the parameter types_first inside jinja code or put there, I don't know exactly what to do, I tried to do it like this:
<script>
$(document).ready(function(e){
var language = $('html').attr('lang');
var selectedFunction;
if(language == "sq"){
selectedFunction = "sq";}
else{
selectedFunction = "sr"; }
</script>
....
<p> Questions: </p>
{{ _({% for type in types_first %}) }}
<div class="checkbox">
<label><input type="checkbox" value="{{ type }}">{{ type }}</label>
</div>
{% endfor %}
First solution (better):
If you want to change lang, you can use i18next framework (http://i18next.com/docs/). It's much simpler solution.
Second solution (worse):
Select via jQuery element you want to change -> use empty() function -> render element with changed values and assign it to selector with append()
You can also combine both solutions. Write function to rerender template and change dynamically langauge. e.g.:
fn_or_elt.empty();
fn_or_elt.append(markup);
fn_or_elt.i18n();

Unescape HTML string from database on twig template

I'm trying to convert a description, which is a string from my database, into HTML. I'm getting the description with {{ projet.description }}, but it seems that in JavaScript, "description" causes a bug in my script... So I create a div with my description on it, make it invisible, and get it with innerHTML.
Twig code
<div id="desc">{{ projet.description }}</div>
<div>
<script type="text/javascript">
var desc = document.getElementById("desc").innerHTML|e('js')|raw;
document.write(desc);
</script>
</div>
CSS
#descr {
display:none;
}
But now, document.write() still returns a string like "<p><em>POKEMON</em></p>". However, I want it in HTML.
I'm almost sure that HTML was escaped, so try it out:
<div id="desc">{{ projet.description|raw }}</div>
See raw filter on twig docs: raw
The raw filter marks the value as being "safe", which means that in an
environment with automatic escaping enabled this variable will not be
escaped if raw is the last filter applied to it
Also:
var desc = document.getElementById("desc").innerHTML|e('js')|raw;
The above snippet is not valid on twig because it isn't surrounded by valid delimiters such as "{{ }}" or "{% %}".

Categories

Resources