How to access array of python in JavaScript from Views in Django? - javascript

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 }};

Related

Django: How to pass python variable value to javascript file?

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>

Passing parameter(s) to Javascript file from Python Flask app through HTML

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.

Send JSON Object while rendering a page with Jinja2

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.

Accessing Express.js local variables in client side JavaScript

Curious if I'm doing this right and if not how you guys would approach this.
I have a Jade template that needs to render some data retrieved from a MongoDB database and I also need to have access to that data inside a client side JavaScript file.
I'm using Express.js and sending the data to the Jade template as follows :
var myMongoDbObject = {name : 'stephen'};
res.render('home', { locals: { data : myMongoDbObject } });
Then inside of home.jade I can do things like :
p Hello #{data.name}!
Which writes out :
Hello stephen!
Now what I want is to also have access to this data object inside a client side JS file so I can manipulate the Object on say a button click before POSTing it back to the server to update the database.
I've been able to accomplish this by saving the "data" object inside a hidden input field in the Jade template and then fetching the value of that field inside my client-side JS file.
Inside home.jade
- local_data = JSON.stringify(data) // data coming in from Express.js
input(type='hidden', value=local_data)#myLocalDataObj
Then in my client side JS file I can access local_data like so :
Inside myLocalFile.js
var localObj = JSON.parse($("#myLocalDataObj").val());
console.log(localObj.name);
However this stringify / parsing business feels messy. I know I can bind the values of my data object to DOM objects in my Jade template and then fetch those values using jQuery, but I'd like to have access to the actual Object that is coming back from Express in my client side JS.
Is my solution optimal, how would you guys accomplish this?
When rendering is done, only the rendered HTML is send to the client. Therefore no variables will be available anymore. What you could do, is instead of writing the object in the input element output the object as rendered JavaScript:
script(type='text/javascript').
var local_data =!{JSON.stringify(data)}
EDIT: Apparently Jade requires a dot after the first closing parenthesis.
I do it a little differently. In my contoller I do this:
res.render('search-directory', {
title: 'My Title',
place_urls: JSON.stringify(placeUrls),
});
And then in the javascript in my jade file I use it like this:
var placeUrls = !{place_urls};
In this example it's used for the twitter bootstrap typeahead plugin. You can then use something like this to parse it if you need to :
jQuery.parseJSON( placeUrls );
Notice also that you can leave out the locals: {} .
Using Jade templating:
If you are inserting #Amberlamps snippet of code above an included static HTML file, remember to specify !!! 5 at the top, to avoid having your styling broken,
in views/index.jade:
!!! 5
script(type='text/javascript')
var local_data =!{JSON.stringify(data)}
include ../www/index.html
This will pass in your local_data variable before the actual static HTML page loads, so that the variable is available globally from the start.
Serverside (using Jade templating engine) - server.js:
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', ensureAuthenticated, function(request, response){
response.render('index', { data: {currentUser: request.user.id} });
});
app.use(express.static(__dirname + '/www'));
You don't need to pass the locals variables in render call, locals variables are globals. On your pug file call don't put keys expression e.g #{}. Just use something like:
base(href=base.url)
where base.url is app.locals.base = { url:'/' };
Have you heard of socket.io? (http://socket.io/).
An easy way to access the object from express would be to open a socket between node.js and your javascript. This way data can be easily passed to the client side and then easily manipulated using javascript. The code wouldn't have to be much, simply a socket.emit() from node.js and a socket.on() from the client. I think that'd be an effective solution!

ASP.NET MVC templates for both client and server

Is this possible? For an example of what I want to achieve, take the Facebook commenting system. Existing comments are rendered on the server, but if I leave a new comment, it is created using AJAX on the client. Ideally, I'd like to store the template for the comment in only one place, and have access to it on both the server (rendered by Razor) and on the client (rendered in Javascript using JSON returned by the server).
Any ideas?
EDIT: I guess another option is to stick with purely server side rendering, and when the user posts a new comment, return the rendered HTML to the browser to be stuffed into the DOM. This isn't quite as nice, but I'd be interested to know if this is possible too.
I would oppose rendering server-side and then sending it back to your JS-script for bandwith and performance. Rather you should use a templating engine that works on both the server and the client. When the client wants to refresh the comments, it requests only the data for the comments and then replaces the old comments html with the new html rendered from the data using the same template that is being used on the server.
I've been using Mustache templating engine to achieve this using PHP and JS. There is a .NET version which I guess works for ASP.NET, and I'm guessing you're using ASP.NET.
So what I do is I make sure I have data formatted in the same way in PHP and JS and then render using a Mustache template.
http://mustache.github.com/
Mustache is simple to use. You take one object and one template and you get the HTML back.
Example object:
object->user = "Kilroy"
object->comment = "was here"
object->edited = true
Example template:
{{user}} {{comment}} {{#edited}}(This comment has been edited){{//edited}}
Result:
Kilroy was here (This commment has been edited)
The approach I've used is having a hidden HTML template with wildcards and/or class names, then on document ready loaded the contents via AJAX/JSON call and finally refreshed or added new items using the same template in javascript.
<ul id="template">
<li>
<span class="message"></span>
<span class="date"></span>
</li>
</ul>
<ul id="comments"></ul>
<script type="text/javascript">
$().ready(function() {
loadComments();
});
function loadComments() {
$.post('#Url.Action("GetComments", "Forum")', {}, function(comments) {
for (i = 0; i < comments.length; i++){
loadComment(comments[i]);
}
}, 'json');
}
function loadComment(comment) {
var template = $('#template li').clone();
template.find('.message').text(comment.message);
template.find('.date').text(comment.date);
$('#comments').append(template);
}
</script>
For new messages, you can post the message to the server and then add it to the list using the loadComment function, or refresh the whole comments list. It's not a complete sample, but hope you get the idea.
I haven't worked with razor or ASP.NET MVC much, but the way I usually approach it using Monorail and NVelocity is this:
Have a template for the page.
For the comments, have a partial template that you include in your main template.
For the AJAX request, use that partial template to render the markup for the comments part. Replace it client side with your preferred method.
This way, will let you have the markup on one place, regardless on if it's a regular request or an ajax request.

Categories

Resources