This question already has answers here:
JavaScript raises SyntaxError with data rendered in Jinja template
(3 answers)
Closed 4 years ago.
I am using Flask to get python lists into HTML. To iterate through the lists and print every elements, I use Javascript.
<script type="text/javascript">
function show_tests(test, desc) {
text = "";
for (i = 0; i < len(desc); i++) {
text += "<tr><td>" + test[i] + "</td><td>" + desc[i] + "</td></tr>";
}
return text;
}
</script>
And the call is
<tbody>
<script type="text/javascript">document.write(show_tests({{ tests }}, {{ descriptions }}));</script>
</tbody>
When I run Flask and open the HTML, the data from JS dosen't show up. Anyone has any idea on why that is?
**BTW: desc and test ALWAYS have same length.
Any help is appreciated!!
EDIT: anyone else having this problem: use jinja! I just learned about it and it's great!!
There's no reason to be using JS here at all. There is nothing interactive here, you should do it directly in Jinja2.
view:
...
return render_template('mytemplate.html', zipped_tests=zip(tests, descriptions))
template:
<tbody>
{% for test, desc in zipped_tests %}
<tr><td>{{ test }}</td><td>{{ desc }}</td></tr>
{% endfor %}
</tbody>
Related
I would like to manipulate the return statement from Template.info.helpers in the way that it will display iterate like:
01...How to do this? Maybe using jquery. Maybe another solution (I treid it with iterate.split("</a></div>");), thought it´s easier if I have an array. I tried a little but there was no satisfactory result. Help please.
.js
Template.info.helpers({
info() {
var iterate ="";
for (var i = 0; i < 10; i++){
iterate += "<div class='row'>" + i + "</div>";
}
return iterate;
}
)};
.html
<template name="info">
Home
</br>
hello
<p>{{info}}</p>
<!--
Gives raw text and returns it as a string -> WORKS NOT FINE:
<div class='row'><a href=0>0</a></div><div class='row'><a href=1>1</a></div> ... and so on
-->
</template>
I am trying to generate random numbers between 1 to 132 (inclusive) using JavaScript, when a user clicks on a button.
So far so good, it generates the value and I am able to get the desired output.
The problem:
I was to use the generated value in a custom Django filter (or whatever it is called). Let me explain it better with my code:
<script type="text/javascript">
function random_generator()
{
var rand = [];
var i;
var j;
var text = "";
for(i = 0; i < 5; ++i)
{
rand[i] = Math.floor((Math.random() * 132) + 1);
text += rand[i];
}
document.getElementById('rand1').innerHTML = text; //Just trying to see if the numbers are generated properly
var text2 = "{%for i in allb %}{%if i.id == " + text + "|add:0 %}<p>{{ i.name }}</p>{% endif %}{%endfor%}";
document.getElementById('rand2').innerHTML = text2;
document.writeln(rand[0]);
}
</script>
Here's what else I tried doing:
<div id="b005" class="modal">
<div id="rand1"></div>
<div id="rand2"></div>
{%for i in allb %}
{%if i.id == **WANT TO USE THE JS VARIABLE HERE**|add:0 %}
<p>{{ i.name }}</p>
{% endif %}
{%endfor%}
</div>
Note:allb is an object that I have passed from my views.py
Is there any other way of doing the same?
Thank you in advance :)
As Daniel already mentioned, you have to first understand what is going on behind the scenes. Your django templates only exist on your server, and all template code gets executed on that server. This template code can be used for non-html rendering as well, as you are doing in your random_generator() script.
But the browser receives only an evaluated version of the templates. So it is impossible to compare your django template code (server-side) to your client-side js.
I am trying to style an HTML table row based on values in that row, but I am stuck on step 1 - styling it at all!
Here's the code I have:
<tr id="tablerow<%=j%>">
<script type="text/javascript">
document.getElementById("tablerow<%=j%>").style.backgroundColor = "red";
</script>
<%=j> is pulling a row number in from the loop that's loading the data from the Access database as it loads the table.
The table rows are not showing up as red!
Then later I am going to use some IF statements in Javascript to color the rows based on data from some of the elements:
var datecheck = new Date;
if (document.getElementById("confirmStatus<%=j%>").value=="P" && (document.getElementById("confirmYear<%=j%>").value < datecheck.getFullYear())) {
document.getElementById("tablerow<%=j%>").style.backgroundColor = "LightCoral"; }
I was able to figure it out - thanks for the help!
Have you checked your JavaScript console?
Atleast it should be document.getElementById not document.getElementByID
Your script execute too early - html not ready yet. Try
<tr id="tablerow<%=j%>">
<script type="text/javascript">
window.addEventListener('load',function(){
document.getElementByID("tablerow<%=j%>").style.backgroundColor = "red";
}
</script>
But it's ugly idea do it by js
I find it better to use custom attributes instead of string concatenation:
<tr data-dbid="<%=j%>" style="background-color:red">
<td><input class="confirmYear" /></td>
<td><input class="confirmStatus" /></td>
</tr>
Then use that when needed:
function checkRow(id) {
var _tr = document.querySelector("[data-dbid=" + id + "]"),
_confirmYear = _tr.querySelector(".confirmYear"),
_confirmStatus = _tr.querySelector(".confirmStatus");
if (_confirmYear.value === "P" && _confirmStatus.value < datecheck.getFullYear())
_tr.style.backgroundColor = "LightCoral";
}
window.addEventListener('load',function(){
[].forEach.call(
document.querySelectorAll("[data-dbid]"),
function(el) { checkRow(el.dataset["dbid"]) }
);
});
I have a django template variable {% clients_list %}
I want to load this in multiple select boxes with same prefixes.
I am writing this code:
$(document).ready(function(){
for (i=1; i<=30; i++){
for(j=0; j<=clients_list.length - 1; j++){
$('#client'+i).append($('<option>')
.text(clients_list[j])
.attr('value', clients_list[j]));
}
}
});
But I am facing this error:
ReferenceError: clients_list is not defined
Help me please!
As always, encode as JSON.
{% load jsonify %}
var clients_list = {{ clients_list|jsonify }};
I am trying to build a very simple tool for use at my work. I work for eBay and currently the tools available are cumbersome for the task. We are asked to compare text and images to check that sellers aren't stealing each others content. I am using the eBay Trading API and the sample HTML/CSS/Javascript code given when the developer account was created. Ultimately what I hope to achieve is a simple page that displays two items' photo and description next to each other. However, right now I am simply trying to edit the sample code given to display the start date of the auction.
My question is this: I am trying add a variable who's value is determined by a response from the API. some of these are provided in the sample however, when I add my own var starttime = items.listingInfo.startTime to the function and add the variable to the HTML table none of the data displays including those that displayed prior to my addition. Unfortunately I don't have more than a rudimentary understanding of javascript and so am unsure if I am even properly phrasing this question, let alone getting the syntax of my addition correct. What am I doing wrong?
below is the sample text with my addition of one declared variable (starttime) and one addition to the HTML table
<html>
<head>
<title>eBay Search Results</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
</head>
<body>
<h1>eBay Search Results</h1>
<div id="results"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = items.listingInfo.startTime;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '' + starttime + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%203g&paginationInput.entriesPerPage=3>
</script>
</body>
</html>"
If you believe listingInfo is an property of individual items, and that it is an object that has the property startTime, then the proper syntax is:
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = item.listingInfo.startTime;
You are currently referencing items which is the array of items, not an individual item.
Update
I looked into this via the URL you put in the comments. The solution to this particular problem is this:
var starttime = item.listingInfo[0].startTime;
I hope that helps. Please review the FAQ; Imho this question falls outside the scope of this site (the question is really quite narrow, and not likely to help anyone else). I recommend Mozilla Developer Network as a source for learning more about JavaScript.