I want to use javascript inside the mustache template. (test.mustache)
https://test.com/?lang=en
<script>
let query = window.location.search;
console.log(query);
</script>
I got ?lang=en with the above code.
{{#cats}}
{{{value}}}
{{/cats}}
i in this code
I want to append ?lang=en after {{link}}.
Is there any way?
No, you can't use JavaScript in your template.
The entire point of the template is to allow code to be extracted. Whatever code is currently executing your template is feeding the template a link variable, which the template is outputting via {{link}}. You need to modify that calling code so that it alters the value of link before it's passed to the template.
Related
I want to replace html file part with javaScript code. Need to use JS events. Since hbs only replaces text, I want to add a js script in html for this purpose. JS code is kept as string and passed as value and I want to execute that from html. Using node js server side rendering with hbs.
TS Code for handlebars parse:
const testScript = "\<script\> function displayDate(o) \{ let x = \"hello\"\;document.getElementById(\"demo\").innerHTML = o\;} </script>";
res.render("home", { testScript });
home html/hbs code:
<div>
{{testScript}}
</div>
result is:
<div>
<script> alert("Hello JavaScript!") </script>
</div>
expected result is:
<script>
function displayDate(o) {
let x = "hello";
document.getElementById("demo").innerHTML = o;
}
</script>
<p id="demo"></p>
If could prevent handlebars from parsing certain tags as altered ones then the expected result could happen.
Could not find a solution by searching using phrases mentioned in this question. So please mention me a solution to keep the string as is for handlebar parsing.
Is it possible to tell handlebars not to parse certain tags?
You need to use triple-stash as per the official documentation. The triple-trash does not escape output.
<div>
{{{testScript}}}
</div>
I'm trying to pass an API Key - which I call on the server side and pass through to an EJS file - into the src attribute on a script tag. When I console.log the string it prints exactly how'd I want but I can't update the src attribute the way I need to, to be able to run the script. I've tried passing in the string variable directly, using template literals etc. Any ideas?
<script>
let myKey = <%- JSON.stringify(key) %>
let string = `https://maps.googleapis.com/maps/api/js?key=${myKey}&callback=initMap`
</script>
<script src= https://maps.googleapis.com/maps/api/js?key=${myKey}&callback=initMap
async defer> </script
You can not use javascript inside tag definition, you can write javascript only in between the script tag, hence the template literal or variable won't work inside src value of script tag
Besides, you can directly use values passed by your route inside HTML part
Write it like this in your code
<script src="https://maps.googleapis.com/maps/api/js?key=<%= key%>&callback=initMap"
async defer> </script>
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
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.
I'm a beginner with JS.
I am working with some JavaScript on a site, and I just want to use only 1 file of JS for determine the actions off the pages. Something like this:
function registerEvents(){
NameOfHTMLDocument = //?? Get the name of the document that called registerEvents function.
switch(NameOfHTMLDocument)
{
case:"homepage":
hmp_btn = document.getElementById("hmp_btn");
hmp_btn.onclick=otherFunction;
break;
case:"otherPage":
elem = document.getElementById("elemID");
elem.onclick=fooFunction;
break;
//etc...
}
}
This function is called with a <body onload="registerEvents()"> that is "inherited" by all the pages.
The question is, How can I get the "NameOfHTMLDocument"?. Because I don't want that JS begin doing weird things when trying to get elements that don't exist.
I found that I can get the URL of the DOM and then play a little with it to get the string that i want, but i'm not sure if this is the better way of doing it.
It Would be nice if you have a better suggestion.
Firstly I would really suggest that you create separate script tags in html documents for functionality that is used only on that page and common functionality in separate file for several reasons:
No code pollution
Ease of change
Smaller download
Secondly, you can use switch on window.location.pathname DOM variable which is everything after domain
instead of homepage, etc..
i.e.
url = vader.samplesite.com/light/saber/
window.location.pathname = /light/saber/
(look at http://www.developertutorials.com/questions/question/q-242.php )
window.location.pathname
All you need to do is some parsing, but I'm sure you'll figure that out :) If not, leave a comment.
In your <body onload="registerEvents()"> pass the object this (the BODY in the DOM) through your event function such as : <body onload="registerEvents( THIS )">.
In your function itself, call the object you passed like object.ownerDocument.URL to get the URL including the HMTL document name or object.ownerDocument.title to get the page title.