In django, I can render a html template from a view action like this:
return render_to_response('video_handle/view.html', {'filename': filename, \
'frame_count': frame_count, 'folder': folder})
This would render the "view.html" template and would give me access to the variables filename, frame_count and folder inside the template, so doing this works perfectly:
<script type="text/javascript">
file_name = '{{filename}}'
frame_count = '{{frame_count}}'
folder = '{{folder}}'
</script>
Now, when i try the same in a coffescrip file, compile the file to javascript and load it to my view.html template, the values of python's variables are not assigned to javascript variables and instead, these variables keep the string value meaning that form example file_name variable keeps the value of this string '{{filename}}' instead of the actual value of the python's variable called filename.
Any idea on what's happening and how to solve it?
If I understand your question right, then what is happening is that CoffeeScript files aren't being processed (only your template is being processed and therefore being passed the variables).
If you absolutely need to pass data from backend to frontend in such a fashion you can just use what you have, JavaScript variables will be accessible to you, so if you load your JavaScript below this <script> tag, you will have access to file_name, frame_count etc.
I'd suggest putting this data in an object, in order to not pollute global namespace with these variables:
<script>
var options = {
fileName : '{{file_name}}',
frameCount : '{{frame_count}}'
// more options here
};
</script>
And then you can use them with dot notation (also in CoffeeScript):
alert options.fileName # should alert the file name
Related
I have a Django template filter to retrieve dictionary items based on the key passed.
{% with data=dict_data|get_data:key %}
I have separately made a template_tag.py file which returns those items.
def get_domain_data(dictionary, key):
p = ast.literal_eval(dictionary)
return p[key]
# data being returned successfully
The issue is in passing the dynamic value of the key in the filter function.
<script>
var key_val = $('#input_id').val();
'{% with data=dict_data|get_domain_data:"'+key_val+'" %}'; //encountering error here
// rest of the code
'{% endwith %}';
</script>
If I hardcode a string value the entire operation works, but I am unable to use the JavaScript variable within the Django {% filter %} function.
As mentionned by Matt Ellen in a comment, the template code is executed on the server, then the generated result is sent to the browser which interprets the javascript parts - so this just can not work this way.
If your data dict is small enough and doesn't depend on javascipt user interactions (ie the javascript only reads it), then the solution is to serialize it to json (in the view itself or using a template filter - one might already exists FWIW), bind it to a javascript variable (in the template) and then let the javascript code use it as just any js object, ie (assuming a "jsonify" template filter):
<script>
var data_dict = {% data_dict|jsonify %};
function do_something() {
var key_val = $('#input_id').val();
var data = data_dict[key_val];
// rest of the code
}
// and you'll probably want to bind do_something to
// some js event handler
</script>
There is a similar issue at Get javascript variable's value in Django url template tag
Providing arg1 can be numeric and the reversed url doesn't contain other instances of the string /12345/ then you can use,
var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString());
I need to access the session value in external js file. I have tried,
var userid = '#HttpContext.Current.Session["UserID"]';
this dosen't work as the variable userid take the right hand side as a string. Can anyone suggest me a idea.
You can access the Session variable in .cshtml and pass it to external javascript file by calling function of external .js file.
var userid = '#Session["UserID"]';
externalJsFunction(userid);
You can assign session to some hidden field and get the hidden field value (session value) in document.ready in external js file.
I have one solution for you.
In layout of your website define any empty div and set its data attribute value with session value if you are using html5 as,
<div id="sessionDiv" data-id="#Session["UserID"]"></div>
Now in your external js file access this div.
var userid=$('#sessionDiv').attr('data-id');
You could add a script tag at the top of the .cshtml file and assign a the userid to a global variable. This variable is then accessible in all javascript files.
index.cshtml
...
<script>
document.mynamespace = {};
document.mynamespace.userid = '#HttpContext.Current.Session["UserID"]';
</script>
....
javascript.js
var userid = document.mynamespace.userid; //do something with userid
mynamespace is a proxy object so that you dont pollute the global namespace.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I'm using the Rain.tpl templating engine for my website. I now have a variable ($username) which I can use in my regular html file with {$username}. This works fine.
I now want to use this same variable in a separate .js file which I load into the thml file using <script src="/js/MySeparateJsFile.js"></script>. I tried using {$username} in it, but that doesn't seem to work. So I thought of setting it from within the html file using Javascript, but I have no clue how I would be able to do that.
Does anybody know how I can insert a javascript variable from within an html file into the .js file methods? All tips are welcome!
In Rain.tpl file declare the username as a js global variable like window.username. Use this global variable in MySeparateJsFile.js file
Rain.tpl
<script>
window.username = "{$username}";
</script>
js file
var username = window.username;
In your html file, right below code:
<script> var username= "{$username}";</script>
Now the variable username will be accessible in your js file
Only .php files will be processed and executed by default. Typically you would output any variables into the template as JavaScript variables, so that they are accessible by all external JavaScript files.
If you have multiple variables, the best way to do this is it JSON encode them on the PHP side, and output the raw result into JavaScript:
<?php
$user = array('username' => $username, 'userId' => $userId);
$userJson = json_encode($user);
In the template
<script>
var user = {$userJson};
</script>
Note when outputting JSON via a template engine, you must ensure that it is outputting the raw data, and not using any filter (such as htmlspecialchars()).
Now, in the external JavaScript or any on page JavaScript you can access the variables:
console.log( user.username );
console.log( user.userId );
The JSON encode method solves two problems:
Prevents XSS vulnerabilities because any malicious content will be escaped by the JSON encoding engine.
The possibility of grouping lots of variables, or using a namespace for your application.
add a data attribute to your script
<script id="myscript" data-username="{$username}" src="/js/MySeparateJsFile.js"></script>
and access it from your javascript:
var username = document.getElementById("myscript").getAttribute("data-username");
I'm trying to pass a string of generated HTML from Python to Javascript. This is the simplified version of my view (using Pyramid framework).
#view_config(route_name='view_page', renderer='templates/page.jinja2', permission='view')
def view_cosmeceutical(request):
gen_html = markdown( ingredient.desc )
return dict(gen_html=gen_html)
From this thread, I saw that I can use {{ variable }} in Javascript too, so in my JS file, I have a function that attempts to change the innerHTML of the element with the id 'content-desc'. But all I'm getting is the string {{ genHTML }} instead of the actual variable containing the generated HTML.
function insertHTML() {
genHTML = '{{gen_html}}';
$('#content-desc').html(genHTML);
}
What am I doing wrong?
One good way to pass data and content from the server-side Python to JavaScript are
JSON embeds in HTML
Separate AJAX calls which serve JSON objects as application/json mime
For the embed approach, I would do somethibng along the lines to export data to the page template as JSON:
import json
gen_html = ...
javascript_data = json.dumps(dict(gen_html=gen_html))
return dict(javascript_data=javascript_data)
Then in the page template pass this to JavaScript global variables:
<script>
window.javascriptData = {{javascript_data}}; // Check need to escape HTML in your case
</script>
And then in JavaScript (keep preferably in a separate static .JS file):
$(document).ready(function() {
$('#content-desc').html(window.javascriptData.gen_html);
});
Also, I would not generate HTML for just passing it to JavaScript in the first place. Instead, I would pass raw data to JavaScript as JSON, and then generate HTML on the client-side from this data using client-side templating. This increases the complexity, but is more "clean" and flexible.
Example microtemplating engines for the client-side JavaScript:
DOM tree based JavaScript template engines
I need to generate a JSON object from server containing data to be cached on client. I placed the following:
<script src='Path to js file on server" />
At the server, I generated my json data and placed them inside the JS file.
I can see the generated JSON object on the client-side something as:
var jsonData = [{}, {}];
However, when I try to access jsonData object, it says, undefined!
Is there another way to generate valid javascript from server side?
Thanks
This is the server-side code:
var items = List<myObj>();
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat(" var jsonData = {0};", json);
var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());
As for client side:
<script src='#Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>
I tried to use this code on the client:
alert(jsonData[0].Id);
It says, jsonData is undefined!
Regards
ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:
You just don't include that js file.
You're trying to access variable before it is initialized;
Variable isn't visible in place, you're trying to access it.
You're not exact in your question and accessing not jsonData, but something like jsonData[0].property
etc.
UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.