I want to hand over a stringarray from my views.py to the template and use this strings for D3.
views.py:
def index(request):
template = loader.get_template("myApp/index.html")
data = ["a","b","c"]
context = RequestContext(request,{"data":data})
return HttpResponse(template.render(context))
index.html:
<html>
<head>
<title>Some project</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<h1>Some project visualisation</h1>
<script type="text/javascript">
var dataArray = {{ data }};
...
At "var dataArray = {{ data }};" I get a syntax error.
I looked this up in the browser-console and my dataArray
seems to look like this:
var dataArray = ['a','b','c']
I have also tried to use json.dumps(data), but I get a similar dataArray like:
var dataArray = ["a","b","c"]
What you are searching for is the 'safe' filter:
context = RequestContext(request,{"data":json.dumps(data)})
...
<script type="text/javascript">
var dataArray = {{ data | safe }};
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-safe
If you use variables more often in your javascript, it would probably make sense to turn off autoescape
Related
I am trying to pass html tag from gsp to template gsp. But i am getting the desired value being passed to the template gsp . Attached the code:
**TestPassValueController**
package sample.test
class TestPassValueController {
def groovyPagesTemplateEngine
def index() {
Map testMap = [:]
def test = '<H1 > " hai test page 123 </H1>'
testMap:[a:"one",b:test]
}
}
**index.gsp**
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title></title>
</head>
<body>
<g:render template='testSample' model="[sample:b]"/>
</body>
</html>
**_testSample.gsp**
<script type="text/javascript">
var sample = ${b};
alert("hai");
alert(sample);
</script>
Thanks
Pooja
You are passing b to testSample and changing b to be sample:
<g:render template='testSample' model="[sample:b]"/>
Then in testSample.gsp, you are referring back to sample now as b:
<script type="text/javascript">
var sample = ${b};
either change model="[b:b]" or change sample to point to '${sample}' and wrap it around quotes like shown.
I am pulling data via a CRM API and successfully rendering that data in the front end of my Google Script web app. But manipulating or formatting this data for the front end is a challenge for me.
In the code below, the Potential Name on the second line is rendering the correct data to the page. But the first line called Quote is showing undefined. This data is the data I am trying to format so that only the last six characters or the string are printed to the page.
Clearly, I must be trying to access the data from the API incorrectly. Could someone please provide me with the correct way to manipulate this data in Google Scripts?
Code.gs
function doGet() {
var templ = HtmlService.createTemplateFromFile('Allied-po');
templ.data = requestRecordFromCRM();
return templ.evaluate()
.setTitle('Purchase Order')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/*Fetch record data from CRM*/
function requestRecordFromCRM() {
requestedId = '1234';
var authToken = 'XXXX';
var zohoRequestUrl = 'https://crm.zoho.com/crm/private/json/Potentials/getRecordById?&authtoken=' + authToken + '&scope=crmapi&id=' + requestedId;
var response = UrlFetchApp.fetch(zohoRequestUrl);
var sanitizedResponse = (response.getContentText());
/*Sanitize json*/
var output = JSON.parse(sanitizedResponse);
Logger.log(output);
/*Declare the variables you want to print*/
var parsedOutput = output.response.result.Potentials.row.FL;
var recordObj = {}
Logger.log(typeof output)
Logger.log(output.response.result.Potentials.row.FL.length)
for (var i = 0; i < output.response.result.Potentials.row.FL.length; i++) {
if (output.response.result.Potentials.row.FL[i].val == 'Potential Name') {
recordObj.potentialName = output.response.result.Potentials.row.FL[i].content
}
}
return (recordObj);
}
Index.html
<html>
<head>
<base target="_blank">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Purchase Order</title>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<div>
Quote: <span id="job-number"><?= data.potentialName ?></span>
</div>
<div>
Potential Name: <?= data.potentialName ?>
</div>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<!-- Load jQuery, jQuery UI, and Bootstrap libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
//Format Job Numbers - return only last six characters in potentialName string
(function() {
var parts = document.getElementById('job-number');
var selectedPart = parts.split(":");
var thePart = selectedPart[0];
return (thePart);
}());
</script>
This particular code retrieves the HTML element but not the innerHTML text
var parts = document.getElementById('job-number');
Instead do this to get the embedded HTML which can used to split the string like so:
var parts = document.getElementById('job-number').innerHTML;
The final code will look like this:
<script>
//Format Job Numbers - return only last six characters in potentialName string
(function() {
var parts = document.getElementById('job-number');
var selectedPart = parts.innerHTML.split(":");
console.log(parts)
console.log(selectedPart)
var thePart = selectedPart[1];
parts.innerHTML = thePart
return (thePart);
}());
</script>
There is limited information on how the object structure looks like? The assumption here is there is six character before ":" in the data.potentialName value. if you rather want exactly six characters you can do this:
var selectedPart = parts.subString(0,6)
Hope that helps!
I have code below. I need to populate a JSON object using mustache. Unfortunately, it shows nothing to me.
<script type="text/javascript">
var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]";
var template = $("#template").html();
Mustache.parse(template);
var rendered = Mustache.render(template, data);
$('#PatrList').html(rendered);
</script>
<body>
<div id="PatrList"></div>
<script id="template" type="x-tmpl-mustache">
{{ #. }}
<div>
PR_ID: <h2> {{PR_ID}} </h2> ---- P_ID: <h2> {{P_ID}} </h2>
</div>
{{ /. }}
</script>
</body>
The problem is that var data is a string and not an object. You need to remove the outer quotation marks or parse the string to an object (given that the delimiter is escaped properly within the string) e.g. with JSON.parse(str) or eval
I Have edited the code, the updated code is below, This code is not able to fetch the keywords meta tag, hence it is not working.
old description: I am trying to concatinate the strings to get the finalUrl, but I am not able to do so becuase of the tags variable. I need to fetch the keywords meta tag of the page and append it to get the finalUrl. Any help?
<script type="text/javascript">
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/details/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
function loadJSON(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
}
function showGameDetail(feed){
var title = feed.title;
var game_url = feed.pscomurl;
var packart_url = feed.Packart;
$("#bnr-ads-box").html("<img src='"+"http://abc.com/"+packart_url+"'>");
}
loadJSON(finalUrl);
</script>
<div id="bnr-ads-box"></div>
<!DOCTYPE html>
<html>
<head>
<meta id="metaK" name="keywords" content="customizable software for QuickBooks, QuickBooks-integrated, Method customization, CRM accounting, Method for QuickBooks, Method CRM, Method blog, Salesforce automation, Method online platform, QuickBooks customization, web-based platform, industry-specific, customer portal, Method Field Services, Method Manufacturing, ERP" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
document.getElementById("demo").innerHTML=finalUrl;
}
</script>
</body>
</html>
change this
var tags="$('meta[name=keywords]').attr("content");";
to
var tags=$('meta[name=keywords]').attr("content");
also use this code var finalUrl = gameurl + tags + jsn;
What you need is to escape the double quotes inside your tags variable, like so:
var tags="$('meta[name=keywords]').attr(\"content\");";
Cris' solution is also fine, but in some case you will need to have two sets of double quotes inside a string so you will be forced to do escaping correctly.
FYI: Escaping is the process of having special characters getting generated in a string which would otherwise cause issues, for instance in javascript you can't have newlines in a string, like this:
var mystring = 'on
a different line'; // <- this causes a syntax error
So one would do the following:
var mystring = 'on\na different line';
You forgot to include the jquery
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="hello"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
alert(finalUrl);
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Tough debatable, you can use an array, which can be concatenated by calling join():
var tags = $('meta[name=keywords]').attr("content");
var data = [
"http://xyz/abc/names/",
encodeURIComponent(tags),
".json?callback=showGameDetail"
].join('');
$("#demo").html(data);
Actually the concat method works on strings too (in chrome at least) but the recommended method is using the plus concatenation string operator
You are however missing some stuff
jQuery library - I assume you want that since you have $(...) in the example
encoding of the string from the keywords - I use encodeURIComponent to handle possible newlines and quotes in the keywords
.
<!DOCTYPE html>
<html>
<head>
<title>Create a URL from keywords</title>
<meta name="keywords" content="These are tags" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function myFunction() {
var tags = $('meta[name=keywords]').attr("content");
var URL ="http://xyz/abc/names/" +
encodeURIComponent(tags) +
".json?callback=showGameDetail";
window.console && console.log(URL);
$("#demo").html(URL);
}
</script>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
I have a controller that passes an array to a twig template, which I want to use in a script written on that page. How would I go about doing that?
I've tried this in my .twig template:
<script>
$(document).ready(function(){
var test = {{ testArray }};
});
</script>
but that only works if it's a string.
You might have to json_encode the array, try this:
<script>
$(document).ready(function(){
var test = {{ testArray|json_encode(constant('JSON_HEX_TAG'))|raw }};
});
</script>
First, send the data json encoded from controller and
then in javascript,
var context= JSON.parse('{{ YourArrayFromController|raw}}');
I do it this way:
Return of the controller test.data then
$test = array('data' => array('one','two'))
Twig:
<div id="test" data-is-test="{{ test.data|json_encode }}"></div>
Js:
$(document).ready(function() {
var test = $('#test').data("isTest");
console.log(test);
});
Output:
["one", "two"]
documentation here
json_encode works well, in combination with the raw filter.
<script>
$(document).ready(function(){
let test = {{ testArray | json_encode(constant('JSON_HEX_TAG')) | raw }};
});
</script>
Don't forget the JSON_HEX_TAG flag.
Otherwise, you can get broken HTML. A string containing <!--<script> is a good way to test that.
In My Controller I Install SerializerBundle
$serializer = $this->get('serializer');
$countries = $this->getDoctrine()->getRepository("QSCORBundle:CountryMaps")->findAll();
$jsonCountries = $serializer->serialize($countries, 'json');
return $this->render('QSCORBundle:Default:index.html.twig',array("countries"=> $jsonCountries));
And In My File Twig
<script type="text/javascript" >
var obj = {{ countries|json_encode|raw }};
var myObject = eval('(' + obj + ')');
console.log(myObject[0]['capital_latitude'] + " " + myObject[0]['capital_longitude']);//for the First Element
</script>