How to put code thymeleaf in an external javascript file? - javascript

I have an external javascript file which is declared in my html file with the following tag:
<script type="text/javascript" th:inline="javascript" th:src="#{/js/gp-aprobarDocumento.js}"></script>
and in gp-aprobarDocumento.js the code shown below:
ventanaAprobacion = function(td)
{
/*<![CDATA[*/
idEntregable = $(td).attr("data-row-id");
idVersion = $(td).attr("data-row-version");
alert("la siguiente viene con el texto dle properties");
alert(/*[[${link.menu.page-certificacion-qa-bandeja-entrada}]]*/);
$(function() {
$("#dialog-aprobar-documento").dialog("open");
});
/*]]>*/
}
Thus when executed the function the window alert is shown empty.
Does somebody know how to put thymeleaf expression in a external javascript?

I think what you want to do it's not possible, I have a similar question (here:How do you access a model attribute with javascript variable)
but in your case you can do something like the this:
in html:
<script type="text/javascript" th:inline="javascript" >
var alertVariable = ${link.menu.page-certificacion-qa-bandeja-entrada};
</script>
and in the javascript the following:
ventanaAprobacion = function(td)
{
...
alert(alertVariable);
...
}
I know that's not really what you want but I have the same problem and I don't think there is any solution.

This worked for me. In my index.html:
<script th:inline="javascript">
/* variable used by index.js */
var referenceId = [[${referenceId}]];
</script>
<script type="text/javascript" th:src="#{/js/index.js}">
</script>
then in my index.js:
function doSomething() {
$.ajax({
type: 'GET',
url: '/api/' + referenceId ,
contentType: 'application/json',
beforeSend: beforeSend
})
}
Hope this helps.

Via DOM:
https://datatables.net/examples/data_sources/js_array.html
If you're looking to create a JS variable from a Thymeleaf object you can add said object to the DOM. I recently did a project where I returned query results to a Java object of type List<> and added that object to the DOM through my Spring Controller.
//Deliver Results Array to the DOM
model.addAttribute("myResult", myResult);
After this object is added to your Thymleaf template model you can access it in your HTML as
th:text="${myResult}"
You can also reference it in your Javascript by simply referencing the name of the model object from the DOM. I haven't been able to get the variable to populate in the seperate JS file without making it global in scope from the HTML file with:
<script th:inline="javascript">
var myResult = [[${myResult}]];
</script>
My JS file looks like this
$(function(){
//Get Thymeleaf DOM Object
console.log(myResult);
});
Returning Result from DOM
Th object in question must be reference-able from within the DOM. You may have better performance with AJAX and creating a controller that returns the data to the client over HTTP. Seems like thymeleaf 3 has other solutions as well : https://github.com/thymeleaf/thymeleaf/issues/395
Hope this helps!

Sure you can.
You can't put Thymeleaf template code in an external JavaScript file, but you can put JavaScript code in a pair of <script> tags in a html template, using a template fragment in the HTML.
Create a new HTML file 'gp-aprobarDocumento.html' in the /template folder, put your function in the script and replace /**/ with ".
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title></title>
<script th:fragment="gp-aprobarDocumento">
ventanaAprobacion = function(td)
{
idEntregable = $(td).attr("data-row-id");
idVersion = $(td).attr("data-row-version");
alert("la siguiente viene con el texto dle properties");
alert("[[${link.menu.page-certificacion-qa-bandeja-entrada}]]");
$(function() {
$("#dialog-aprobar-documento").dialog("open");
});
}
</script>
</head>
<body>
</body>
</html>
And add a th:replace <script> tag in your html file.
<script th:replace="gp-aprobarDocumento :: gp-aprobarDocumento"></script>

Related

Call .js function in another.js

I have...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="xpath.js"></script>
<script src="myscript.js"></script>
</head>
<body>
<!-- some html code -->
</body>
</html>
myscript.js
$( document ).ready(function() {
$("body").click(function(event){
console.log(event.target);
//call xpath.js (getxpath(event.target))
});
});
xpath.js
here stored locally
How do I achieve this..?
Accessing functions from another file
Code separation between files does not matter (You could pack them all in a single file without any problem). Execution order and scopes do. All scripts loaded on a web page share a same global scope, which is window, and can add variables to it.
Most libraries do this so you can access them (jQuery creates a global $ variable, for example, and you can use it anywhere).
Your Xpath script, however, does not, because it's not meant to be directly embedded into a webpage. It's part of a Firefox addon. So in order to make it accessible, you need to modify it.
Modifying xpath.js
At the beginning, change this:
define([
"firebug/lib/string"
],
function(Str) {
... to this:
window.Xpath = new (function(Str) {
And at the end, change this:
});
... to this:
})();
Using it
Now that you did this, you have a global Xpath Object that you can access like this:
$(function() {
$("body").click(function(event){
console.log(Xpath.getElementXPath(event.target));
});
});

Handlebars Pass a string or Handlebars AST to Handlebars compile

I know its been asked many times, I have looked at the answers and not sure where I am going wrong.
I have looked at the docs on Handlebarsjs and followed a tutorial and both times I am getting the same error.
<!DOCTYPE html>
<html>
<head>
<script src="handlebars-v1.3.0.js"></script>
<script src="jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<script id="header" type="text/x-handlebars-template">
div {{ headerTitle }} div
Today is {{weekDay}}
</script>
</body>
</html>
And this is my Javascript
var theData = {headerTitle:"name", weekDay:"monday"}
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
I keep on getting the following error and i am unsure why
Uncaught Error: You must pass a string or Handlebars AST to Handlebars.compile.
You passed undefined
You are running Handlebars.compile() before theTemplateScript is loaded into the DOM. Move your test.js down below the template script and you should be good to go.
Moving the scripts to the bottom of the page also worked for me.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script id="header" type="text/x-handlebars-template">
div {{ headerTitle }} div
Today is {{weekDay}}
</script>
<script src="handlebars-v1.3.0.js"></script>
<script src="jquery.min.js"></script>
<script src="test.js"></script>
</body>
</html>
As others have said, the problem is that you are running Handlebars.compile() before the TemplateScript is loaded into the DOM.
Putting your javascript calls in $(document).ready() you make sure all the html is loaded first.
var theData = {headerTitle:"name", weekDay:"monday"}
$(document).ready(function(){
var theData = {headerTitle:"name", weekDay:"monday"}
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
});
in my case i was trying to assign some value to more deeper steps therefore, i faced the error.
Before my code was
app.use(function (req, res, next) {
res.locals.partials.weather = {}; = getWeatherData();
next();
});
and the problem was
res.locals.partials.weather
after removing the layer partial my problem was gone.
and the final code is
app.use(function (req, res, next) {
res.locals.weather = getWeatherData();
next();
});
In my case I got the same error but the issue was a typo in the template script in the html page. I had 'prouct-template' should have been 'product-template':
<script id="prouct-template" type="text/x-handlebars-template">
...
</script>
Once I fixed the typo the error went away and page loaded ok.
A bit of modification is needed in JavaScript file. I had the same issue. In my code, I called "handlebars" from Views (following explanation is with respect to views).
Include following in initialize function(init) of View :
theTemplate = Handlebars.compile(theTemplateScript);
In render write the remaining code :
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
The correct way is to precompile the Handler, Store in file and then assign it to theTemplate.
You're using Handlebars.compile() before the template script loads. One simple trick would do the work for you. Use the defer tag in your script so that the entire body loads before the script runs in your <head> tag.
<head>
<script src="" defer> </script>
</head>

Change the default browser behaviour of interpreting script tag

We all know what <script src="/something.js"></script> does. That file is loaded in the page and the script is run.
Is there any way to override the default behaviour of interpreting <script> elements?
I want the same syntax (<script src='...'></script>) that will only get the code from something.js (probably via XHR/jQuery ajax) and pass it to a foo (...) {...} function. Then I will care what I will do with it.
To clarify the problem:
I can easily create a pseudo <script> tag alternative using:
<div data-script-src="/1.js"></div>
<div data-script-src="/2.js"></div>
<div data-script-src="/3.js"></div>
<div data-script-src="/4.js"></div>
And then in the js side I would do:
var $scripts = $("[data-script-src]")
, scriptContents = [];
(function loadInOrder (i) {
if (!$scripts[i]) { alert("Loaded"); }
$.ajax($($scripts[i]).attr("data-script-src"), function (data) {
scriptContents[i] = data;
loadInOrder(++i);
});
})(0);
But how can I replace div[data-script] with <script>? How can I force the browser NOT to load the <script> tags that have the attribute data-load="false", for example?
I think your best bet here is to use onbeforescriptexecute. This event fires right before the script executes, so you can then modify the type attribute to something other than text/javascript (thus telling the browser not to execute the contents). This will still load the data from the server.
Unfortunately, onbeforescriptexecute is only supported in FF/Opera.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
document.addEventListener("beforescriptexecute", function (e) {
console.log(e.target.innerHTML || e.target.src);
}, true);
</script>
<script>
console.log("12");
</script>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
Hi
</body>
</html>
The console output will be:
'console.log("12")'
'http://code.jquery.com/jquery-1.10.2.min.js'
Create Your own PHP file, which will work as a kind of a gate. Then
<?php
$file = file_get_contents(your_url);
$file = str_replace('<script', '<myscript', $file);
$file = str_replace('</script>', '</myscript>', $file);
echo $file;
?>
And then if needed add Your type of real script that will search for myscript tags and run Javascript code...
You can use div element as well (if scripts are loaded in body, and You need validation):
substitute: '<script' -> '<div data-id="my-script" '
substitute: '<script' -> '</div>'
PS. I don't know if these are Your sites or sites from internet, that You want the default behaviour to be overwritten. So always be careful of what You are "file_getting_contents" because, this will be echoed directly to Your browser.

how Javascript call to a function of a external file?

i made a html page with this coding
<html>
<head>
<script src="../a.js">
var u=document.URL; var i='t4527878445'; m_web(u,i);
</script>
</head>
<body>
</body>
</html>
In a.js i have this code
function m_web(u,i) {
alert('l');
alert('u');
}
but my webpage is unable to call this function which is coded in an external file. i am not getting any alert with this. i don't know what is problem. plz tell me simple solution for this.
thanx in advance
A single <script> tag can link to an external resource using the src attribute OR contain inline JavaScript code, but it can't do both at the same time. If you specify a src attribute any content between the <script src="foo.js"> tag and the </script> tag is ignored.
Since you want to load the external JS file, and then execute some JavaScript code, you'll need two separate tags to do so:
<script src="../a.js"></script>
<script>
// your code
</script>
plz write your code like below
<script src="../a.js"></script> </script>
//^^^^^^^^^^^^^^^^^^ first close script tag of linked js file
<script type="text/javascript">// then call your inline jscode
var u=document.URL; var i='t4527878445'; m_web(u,i);
</script>
Try
you are not closing script tag
<script src="../a.js"></script>
^//added closing script tag
<script>
var u=document.URL; var i='t4527878445'; m_web(u,i);
</script>
to alert what you pass use
function m_web(u,i) {
alert(i);
alert(u);
}

access head javascript variable in .js file jquery function

I have a javascript variable in the head of my dom and I need to access it in an external js file but it seems to come up undefined.
In my head I have something like.
<head>
<script type="text/javascript">
var overlayAlignment = ["left:20px","right:40px","left:50px"];
</script>
</head>
external .js file
$(document).ready(function () {
alert(overlayAlignment[0]);
});
In my external js file I want to use the variable but something like this comes up undefined all the time, any idea what I am doing wrong.
I found that I could run a function from the external .js in the head to set the overlayAlignment variable if I add the overlayAlignment variable to the .js file.
<head>
<script type="text/javascript">
setOverlayAlignment("value1", "value2", "values3");
</script>
</head>
external .js file
function setOverlayAlignment(value1, value2, value3) {
overlayalignment[0] = value1;
overlayalignment[1] = value2;
overlayalignment[2] = value3;
}
This still comes up as undefined when I try to use it in my jquery function however. Strange, I thought $(document).ready was to tell the function to wait till the dom is loaded to run, if that is the case why is overlayAlignment undefined when it runs?
I need to do it like this because the overlayAlignment variable values are only known at runtime.
You need to surround the JavaScript code in the head with script tags.
Therefore, your first example should really be:
<head>
<script>
var overlayAlignment = ["left:20px","right:40px","left:50px"];
</script>
</head>
And your second should be:
<head>
<script>
setOverlayAlignment("value1", "value2", "values3");
</script>
</head>
Weird just tried this and it worked. Strange I thought window.onload and $(document).ready were the same thing.
window.onload = function () {
$(document).ready(function () {
alert(overlayAlignment[0]);
});
}
Apparently overlayAlignment was not ready when $(document).ready was called but it will be available after window.onload.

Categories

Resources