I have an app written in webapp2 using Google App Engine. The page I want to render needs to use some variables from the backend. How can I pass variables from Python to Javascript as a JSON object?
Thanks!
//define your values dictionary
template_values = {"name": name,
"other_value" : other values}
//render your template
template = jinja_environment.get_template("path to my html file")
return self.response.write(template.render(template_values))
then in your html you can use {{name}}
In your template file, you'd need to do something like:
<script>
var your_js_object = {{your_json_dump}}
</script>
This isn't ideal, as it means that your_js_object is global, but you'd have access to the object in your js files.
Related
I am writing this array in Views in Django:
address=["Main Address"]
and passing in dic. and accessing in Java Script in HTML page:
address={{context.lat_long.address}}
addMarker(address,{lat: property_lat, lng: property_long}, "red");
But it is not working at all
You need to understand how Django templating works.
The template data (Jinja) are generated in the backend, before sending the page.
The JS code is runing in the front.
You can do it in the following way,
In django views,
address=["Main Address"]
return render_template('page.html', address=address)
In the page.html and the attached javascript, you can access the variable as,
var a = {{ address }};
I've a function in views.py which returns latitude and longitude:
return render(request, 'map.html', {'lat_lng':lat_lng})
and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it.
I tried all below stack answers but none worked for me:
Django Template Variables and Javascript
Passing django variables to javascript
How to use Django variable in JavaScript file?
Passing Python Data to JavaScript via Django
You can take advantage of json_script template tag. In your template do this
{{ lat_lng|json_script:"lat_lng" }}
Then in your javascript file you can access this variable like
const lat_lng = JSON.parse(document.getElementById("lat_lng").textContent);
One simple way to do it is to append the following snippet at the top of your template html file(the one that imports your javascript file):
<script type="text/javascript">
const LAT_LNG = "{{ lat_lng }}"; // Or pass it through a function
</script>
when I try to use lat_lng in separate js file then I'm not able to access it.
You can't use a django template variable in a static file. The static files will be returned in a way that bypasses Django's typical request processing.
Instead, set the variables on data-* attributes on an known HTML element, then get the element, access the attribute and use the value that way.
Be sure when that getting the variable in a script tag is before including the separate js file
Exmple :
<script type="text/javascript">
var variable = "{{myV}}";
</script>
<script type="text/javascript" src="myJsFile.js"></script>
I'm using Spring Boot with the Thymeleaf template engine. I have a HTML called clients.html file in the templates folder and a JavaScript file called functions.js in the static folder. I want to send from the controller to the JavaScript file a List.
I have tried using this syntax in the JavaScript file:
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
But I don't recive anything. I have tried using the script tag in the HTML and it worked, but I want to have the JS code in a separate file and not in a script tag with all my html code.
The controller where I send the information to the JS looks like this:
#GetMapping("/articulos")
public ModelAndView showHielo(#RequestParam(name = "numcli", required = false) String numcli){
ModelAndView mav = new ModelAndView(ViewConstant.ARTICULOS);
mav.addObject("numeroArticulos", searchMovimNumarts(" 133"));
return mav;
}
Where the controller send the searchMovimNumarts() method with the name of "numeroArticulos" the one returns a List.
And the JS file where I want to recive the "numeroArticulos" object looks like this:
/*This variable stores data sended by the controller*/
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
console.log(listaArticulos);
I want to console log the content of the List using a JS file and no the html
tag. How can I solve this?
Thymeleaf template engine parses only the template file(html files). So you have to include those variables defined in the controller into the embedded js code. However You don't have to put your entire js code in your html. Have only that part of code that refer to those variables in script tag.
<script>
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
</script>
and refer them in your external js after this
<script src="/js/externalscript.js"></script>
I'm moving one of our web applications from Drupal to an ASP.net MVC Web Application.
One of the Drupal functions gets some data from a web service and converts it to a JS Array, as follows:
foreach ($xml_result->JobList->JobDetail as $job_detail) {
// dsm((array)$job_detail);
$open_job_details[] = array("east"=>(string)$job_detail->Easting,"north"=>(string)$job_detail->Northing, "duedate"=>(string)$job_detail->openDate);
}
//dsm($open_job_details);
$open_jobs_data = json_encode($open_job_details);
drupal_add_js(array('open_jobs' => array('open_newjobs' => $open_jobs_data)), 'setting');
In the Javascript file, it is accessed using;
var openJobsData = JSON.parse(Drupal.settings.open_jobs.open_newjobs);
Is there a simple way to access a server side variable in the JS file in .NET? I can call the web service and get the relevant data from the XML file but not sure how to access it in the JS file.
Thanks
You can use Strongly Typed view to create cshtml page
if you want to access JSON object
View1.cshtml
#model mvcApplication1.Models.model1
#{
var serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
var jsonModel = serializer.Serialize(Model);
}
var JsonData = #Html.Raw(jsonModel); // declare a javascript variable and use it
if you want to access server variable at cshtml page
just use # to access server-side variables
after getting the value you can use javascript variable in another js file
Declare your javascript variable outside
$(document).ready(function()
{}
or before using the variable
you can use that variable in Javascript file.
I am building a Python/Flask based web app. The python script produces a dictionary of words and their corresponding weights. I have a javascript file (let's call it custom.js), which I call from the output.html. The way this javascript works is that it takes this dictionary and then uses d3.v3.min.js and d3.layout.cloud.js to create a wordcloud. When the dictionary is hard-coded into custom.js, the output file shows the wordcloud. However, the dictionary values will change depending on other parameters in the python script. Therefore, I would like to pass this dictionary from Python to custom.js. I am not sure how to do that.
I know that the parameters could be passed to HTML using {{ params |safe }}, but I am trying to figure out how to do that so that custom.js will receive the parameters (dictionary of words and weights, in this case) and word clouds can be rendered dynamically.
Thank you in advance!
If I understood you correctly you need to create a view function (a route) in the flask backend with url like this /get_dictionary. This function can look like this:
from flask import request, jsonify
...
#app.route('/get_dictionary'):
def get_dictionary():
...
your_dictionary = []
# Fill in your_dictionary with data
...
render_template('your_template.html', your_dictionary=your_dictionary)
EDIT:
You can pass the data from flask to script section of the html template using standard jinja2 notation:
<html>
<head>
<script>
your_dictionary = {{ your_dictionary | tojson }}
<!-- Do what you need with your_dictionary -->
</script>
...
</head>
...
you can try define a var in your template html, like this:
<script>
var your_var = '{{ value }}'
</script>
then use "your_var" in external js file. But please make sure above definition is at ahead of your js file refer.