Use TAL:defined variable in javascript - javascript

I'm creating a page template for a plone-based website. I've defined some variables using the template attribute language:
<tal:macro metal:define-macro="sample" tal:define="var python: here.getThisVar();">
Now I would like to use var in an extern javascript file, that I call by clicking a button inside my template. How can I transfer my variable, that I can work with it in my javascript file?

In your template define a javascript variable by writing it out using TAL like this:
<script type="text/javascript" tal:content="string:var MY_VAR=${view/myVar};"></script>
Now MY_VAR should be available in scope of your external js as long as you call it after the line above...

Another way: inject your variable into HTML using an HTML 5 data attribute::
<div id="myVar" tal:attributes="data-myVar python:here.getThisVar();">
Then read it using JAvaScript/jQuery::
$('#myVar').data('myVar');

There are a variety of ways to do it. All involve constructing Javascript code as if it's text, then returning the result for insertion into a page or rendering as a JS resource in the javascript registry.
If you'd like a robust example that includes provisions for message translatability and works with the JS resource registry, see the way Plone itself does it: https://github.com/plone/Products.CMFPlone/blob/4.2.7/Products/CMFPlone/browser/jsvariables.py

Related

Using Ruby Variables in JavaScript

I'm new to Ruby so I had a question in regards to using some variables throughout my codebase. I have a variable declared in my Ruby file as follows:
#pages = 350
Now, I know that in HAML, I can simply do:
-if #pages = 350, and in HAML with inline javascript, I can do something like:
:javascript
console.log("#{#pages}");
However, I am linking an external JavaScript file in my HAML document, and I was wondering if it would be possible to use my Ruby variables in my external JS document? I need some variables in order to build what I am trying to build. Thanks!
Update as per one of the answers:
In my HAML file, I have the following:
:javascript
printPages(3);
In my external JS file, I have:
$(function() {
window.printPages = function(pages) {
console.log(pages);
}
});
I you are loading static javascript files I really would not recommend trying to insert variables into that code.
Instead, think about how you would provide that to your javascript code.
You could send it to that code as an argument.
<script type="text/javascript" src="./my-external-script.js"></script>
:javascript
runMyExternalFunction(#{#pages})
Or you could add the variable as a data attribute on your page, and your javascript could look for that when it loads.
Haml:
%body data-pages=#pages
JS:
console.log(document.body.dataset.pages) // value of #pages
Update about your javascript:
Using jquery's on page ready event $() for declaring the function is a bad idea. That means that it waits for everything on the page to be compeletely loaded, and then declares the function your page needs.
What you should be doing is setting up all the function that will be needed right away, and then calling those functions when the page is loaded.
They way you have it, the page loads, printPages() is executed (which doesn't exist yet), and then after all that printPages is created and put into the global scope.
So remove the $() from your external script and add it to your HAML instead.
In fact, if your aren't doing anything super fancy with transpiling or bundling, then you can simply declare the function in your external JS file, and it will be available globally. This doesn't work with your code because they way you've declared the function, it would only be available to code within that $() callback.
// js file
function printPages(pages) {
console.log(pages);
}
HAML:
$(() => {
printPages({#pages})
})

Defining Django context variable in Jquery giving me error?

I am trying to use a django context variable in my jquery script.
First of all, this WORKS:
index.html
<head>
<script type="text/javascript">
var page_size = {{page_obj.paginator.num_pages}};
</script>
<script type="text/javascript" src="{% static 'js/paginate.js' %}"></script>
</head>
js/paginate.js
$(document).ready( function() {
alert(page_size); //THIS WORKS!!!
});
However, I didn't want the users to be able to be view my variables so I simply added the global variable declaration in my "paginate.js" file:
index.html
<head>
<script type="text/javascript" src="{% static 'js/paginate.js' %}"></script>
</head>
js/paginate.js
var page_size = {{page_obj.paginator.num_pages}}; //Exactly the same as the above!!
$(document).ready( function() {
alert(page_size); //ERROR!!!
});
Strangely enough, this gives me an error:
SyntaxError: invalid property id
var page_size = {{page_obj.paginator.num_pages}};
I have no idea why the first one works while the second one gives me an error, because they are exactly the same... Maybe because I'm second one is declaration in Jquery..?? Any idea??
Thanks..
TL;DR
You can't pass a variable to a static files because they aren't parse by the Django template processor.
Explanations
Your first example works because you set the {{ page_obj.paginator.num_pages }} in your template, which will be parsed and transform into a number. When you're returning a template with Django (through any render method), only the template will be rendered. CSS and Javascript linked in your template are called static files: that means they're ressources which will not be read by the Django template processor.
Imagine that you want to insert your variable in an img in your page. Does it makes any sense? No? However, it's the same behavior.
How to do this then?
You can get the data either via an AJAX request in your Javascript file (warning: a bit overkill for your case here), or using your first method.
Related topic:
Passing Python Data to JavaScript via Django
Passing parameters to the Javascript code on a page using django templates?
In Django, if we need to pass variables from a view to a JS/html file, we'll have to ensure that the file is parsed by the django template engine. In other words the file has to be served by Django.
Whereas here, the included Javascript isn't processed by the Django template processor on the server, so that won't work.
If you need to pass template variables to be used in JS files, then you have to use the first method mentioned in the question i.e. create a small <script> block wherein some global variable is declared to contain those template variables. Then, any JS file can get the values by looking for the global js variable.

Give preference to JS file function over HTML file

I have two functions of the same name; let's say foo().
One in the HTML file and one in the JS file, which is included in the HTML file. The problem is I want to give preference to the JS file function rather than the HTML file function.
Is there any way to do that, or is there any syntax in JavaScript like [JSFileName].foo(), that may perhaps call the function in the JS file?
Not sure why you want to have two identically-named functions.
The snarky answer is: Just remove the reference to the function you don't want. (If you have control over your html, such a situation shouldn't exist.)
The answer you're looking for: Place the external script tag after the inline script tag.
Make sure the script tag for the js file is after the HTML script tag in which foo is declared.
It's not clear from your question why you have two functions named foo, but based on your [JSFileName].foo() attempt at a solution, I might suggest using objects as namespaces. In your script you could do:
var myScriptFunctions = {
foo: function() {
// do foo stuff
}
}
You can call it with myScriptFunctions.foo() and you won't have two functions competing for the global name foo.

Is there a way to send variables to javascript files?

is it possible to do something like this
to send the value id=3 to the js file
<script src="http://site.com/js/loader.js?id=3" ....
otherwise what's the approach to do that?
No, that won't work.
Just set the variables before you load the file:
<script>var id = 3;</script>
<script src="http://site.com/js/loader.js" ....
Since all the scripts share a global namespace, you'll be able to access the id variable from inside your loader.js file.
Of course you should think about the style and implications of using global vars to achieve that. Using a global object that hold these config variables might be a cleaner approach.
If that is just a javascript file, you can just define the variable before load it.
<script>
var id = 3;
</script>
<script src="http://site.com/js/loader.js" ....
It would work, but not if your .js URL is just for a static file. If you wrote server-side code that output JavaScript, then you could output custom JavaScript based on the query string.
This is probably overkill for what you're trying to achieve.
k so this question has pretty much been answered. But there is another approach, which may or may not be suitable for you. If you want to render script conditionally or fetch a certain script for a certain id. You can declare it in a serverside script
http://site.com/js/loader.js.php?id=1
In the loader.js.php
Just use the following line in the beginning
<?
header("Content-type: text/javascript");//To declare it is a javascript file
$id=$_REQUEST['id'];
?>
//Normal js continues after this
//When you need to use the variable, just use
var id=<?=$id?>

How to split JavaScript code into multiple files and use them without including them via script tag in HTML?

I am making use of constructors (classes) extensively and would like each constructor to be in a separate file (something like Java). Suppose I have constructors say Class1, Class2, ... Class10 and I only want to use Class1 and Class5 I need to use script tags to include Class1.js and Class2.js into the HTML page. Later if I also need to use Class3 and Class6 I again need to go to the HTML page and add script tags for them. Maintenance with this approach is too poor.
Is there something in JavaScript similar to include directive of C? If not, is there a way to emulate this behavior?
You can use jQuery.getScript:
http://api.jquery.com/jQuery.getScript
Or any of the many javascript loaders like YUI, JSLoader, etc. See comparison here:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
You can use something like this:
jsimport = function(url) {
var _head = document.getElementsByTagName("head")[0];
var _script = document.createElement('script');
_script.type = 'text/javascript';
_script.src = url;
_head.appendChild(_script);
}
then use it in your code like:
jsimport("example.class.js");
Be careful to use this when the head is already in the DOM, else it won't work.
Yes: You can create script tags from JavaScript and load required classes on demand.
See here for a couple of solutions: http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
With careful use of id attributes or a global variable that contains "already loaded" scripts, it should be possible to develop a dependency resolution framework for JavaScript like Maven or OSGi for Java.
When we are talking about JavaScript, I feel it is better to include one file that includes everything you need instead of requesting a new file every time you need something that you don't currently have access to.
Each time you send out for another file, the browser will do many things. It checks if the requested file can in fact be found by sending an HTTPRequest, and if the browser has already seen this, is it cached and unchanged?
What you are wanting to do is not in the spirit of JavaScript. Doing what you are explaining will produce addition load times, and you wouldn't be able to do anything until the file has completely loaded, which creates wait times.
It would be better to use one file for this, include at the inner end of the </body tag (which won't cause the browser to wait until the script is done to load the page), then create one simple function that will execute when the page is completely loaded.
For example:
<html>
<head></head>
<body>
<!-- HTML code here... -->
<script src="javascript.js"></script>
<script>
(function r(f) {
/in/.test(document.readyState) ? setTimeout('r(' + f + ')', 9) : f()
})(function() {
// When the page has completey loaded
alert("DOM has loaded and is ready!");
});
</script>
</body>
</html>
you can include one js file into another js file by doing something like this in the begginig of your js file:
document.write("<script type='text/javascript' src='another.js'></script>");
The best approach in your situation is using of compiler of some kind. The greatest one is Google Closure Compiler. This is part of Google Closure Libraty which has structure similar to what you described.

Categories

Resources