I have several xsl files that need to include common xsl file. So instead of including the javascript files in each one of them I would like to create a Common.xsl that will include the java script files and all xsl files will include it.
The question is how to do that?
I tried some suggested methods using including javascript file but with no success, in the browser console I get errors:
Uncaught ReferenceError: jQuery is not defined
Uncaught ReferenceError: $ is not defined
It looks like the jquery was not included.
I tried to do something like this:
<"script type="text/javascript" src="common.js" />
or
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "../jquery/jquery-1.9.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script)
})();
Edit:
I answered my question see answer below.
<xsl:element name="script">
<xsl:attribute name="src">common.js</xsl:attribute>
/* common code */
</xsl:element>
That should do the trick
I solved my issue by the following code using xsl instead of javascript files:
I have created a Common.xsl file that includes all my common javascript files.
Common.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="Common">
<link rel="stylesheet" href="SiteRef_getCSS?CSSName=Site/site.css" type="text/css"/>
<script type="text/javascript" src="SiteRef_getJS?JSName=jquery/jquery-1.11.1.min.js"/>
<script type="text/javascript" src="SiteRef_getJS?JSName=Site/common.js"/>
<script type="text/javascript" src="SiteRef_getJS?JSName=Site/MessagesConstants.js"/>
<script type="text/javascript" src="SiteRef_getJS?JSName=Site/win_functions.js"/>
<script type="text/javascript" src="SiteRef_getJS?JSName=Site/resizeFunctions.js"/>
</xsl:template>
On every xsl file that need those includes I added the following lines:
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:include href="common/Common.xsl"/> <!-- Here I include the Common.xsl -->
<xsl:template match="/Reflection">
<xsl:text disable-output-escaping='yes'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "SiteRef_getCSS?CSSName=Site/xhtml1-transitional.dtd"></xsl:text>
<html>
<head>
<title><xsl:value-of select="Localization/ViewAbout"/></title>
<xsl:call-template name="Common"/> <!-- Here I apply the tamplate of the common includes -->
<body>
.
.
.
</body>
</xsl:template>
</xsl:transform>
In order resolve the include URI (see xsl:include) in my java application server I had to implement the URIResolver resolve() function:
public class XslURIResolver implements URIResolver
{
private static final String XSL_PATH = System.getProperty("user.dir") + File.separatorChar + INetlayerConstants.c_UI_PATH + INetlayerConstants.c_XSL_PATH;
#Override
public Source resolve(String href, String base) throws TransformerException
{
DOMSource xslDomSource;
try
{
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
InputStream in = new FileInputStream(XSL_PATH + href);
InputSource xslInputSource = new InputSource(in);
Document xslDoc = dBuilder.parse(xslInputSource);
xslDomSource = new DOMSource(xslDoc);
xslDomSource.setSystemId(XSL_PATH + href);
return xslDomSource;
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And then before transformation I set the URIResolver:
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setURIResolver(new XslURIResolver());
That's about it, hope it helps someone...
Related
I see this question with hundreds of answers, none of which have worked for me yet. I am building a simple asset tracker. My controller has two functions
#Controller
public class GpsController {
private double bestLat = 0.0;
private double bestLon = 0.0;
private double divisor = 10000000.0;
#GetMapping("/map")
public String map(Model model) {
model.addAttribute("latitude", bestLat);
model.addAttribute("longitude", bestLon);
return "map";
}
#PostMapping("/addlocation")
public void addLocation(#RequestBody GpsMessage message) {
if(message.getGpsTimestamp() == 0L) {
bestLat = message.getTriLat();
bestLon = message.getTriLon();
} else {
bestLat = message.getGpsLat() / divisor;
bestLon = message.getGpsLon() / divisor;
}
DbConnection.writeLocation(message);
}
}
I'm using Thymeleaf in /map to pass the latitude and longitude into the JS for the Google Maps API. The program works just fine, but I get these errors from Thymeleaf. I could ignore it but I prefer to find what is causing it.
2022-06-13 05:18:14.177 ERROR 28188 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "addlocation": Error resolving template [addlocation], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [addlocation], template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:869) ~[thymeleaf-3.0.15.RELEASE.jar:3.0.15.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.15.RELEASE.jar:3.0.15.RELEASE]*
What confuses me is that it is complaining about the addLocation method when it is not using thymeleaf.
In resources, I have index.html, index.js, and style.css inside the static folder and the map.html file under templates.
map.html looks like this if it matters...
<!DOCTYPE html>
<!--
#license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add Map</title>
<meta http-equiv="refresh" content="10">
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<script th:inline="javascript">
var myLat = /*[[${latitude}]]*/;
var myLon = /*[[${longitude}]]*/;
</script>
</head>
<body>
<!--The div element for the map -->
<div id="map"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&v=weekly"
defer
></script>
</body>
</html>
I have an issue with a web view I'm using.
The javascript files used to render the view properly MUST be loaded in a specific order.
On browser (chrome mobile; safari desktop, ...) it works well.
However in my web view the result is unpredictable.
This is one of the latests failing run I had:
The HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()"></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/script1.js"></script>
<script src="js/script2.js"></script>
<script src="js/script3.js"></script>
<script src="js/script4.js"></script>
... More scripts...
</body>
</html>
Here is the Java code:
mWebView = (WebView)findViewById(R.id.webView);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setHorizontalFadingEdgeEnabled(false);
mWebView.setScrollbarFadingEnabled(false);
mWebView.setVerticalFadingEdgeEnabled(false);
mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
mWebView.loadUrl("http://192.168.1.24:8000/path/to/index.html");
The issue is that randomly, javascript files are interpreted in wrong order or just not loaded.
From my understanding, javascript MUST be loaded in declaration order.
Am I wrong ?
Is there anything I can do to change that behavior ? (other than concatenating all JS together..)
Your scripts will work on the web site but for make it work on the android you need to load the scripts manually. See the function how it load the script from assets.
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
See Here Example
also make sure you enabled JS:
webSettings.setJavaScriptEnabled(true);
and the manifest ofcourse:
<uses-permission android:name="android.permission.INTERNET" />
When I try to pass my Html into WebBrowser.DocumentText which include JS.
<script src="jquery\script.js"> </script>
It is same path with my executable. But when open in Winform, it is unable to find the 'script.js'..
But when you enter the full path of script, it is working.
StreamReader stringReader = new StreamReader(htmlFilename, Encoding.Default);
StringBuilder sb = new StringBuilder();
string temp;
while (!String.IsNullOrEmpty(temp = stringReader.ReadLine()))
{
sb.AppendLine(temp);
}
stringReader.Close();
return sb.ToString();
Eventually I read html into StringBuilder, and pass it to WebBrowser.DocumentText. Any other way to make it works without giving full path of the script?
You can give like this into your HTML document
<script type="text/javascript" src="../jquery\script.js"></script>
in HTML Page
<html>
<head>
<script type="text/javascript" src={Fullpath}></script>
</head>
<body>
</body>
</html>
in C#
string ScriptfullPath = Application.StartupPath.ToString()+"\\jquery\\script.js";;
string htmlContent;
using (StreamReader reader = new StreamReader(Application.StartupPath + \\JQuery\\sample.htm"))
{
htmlContent = reader.ReadToEnd();
}
htmlContent = htmlContent.Replace("{Fullpath}", ScriptfullPath);
Then your HTML document will use Script file with full path...
First let me thank you for the assistance, I am new to Javascript, and want to learn to parse a >.xml file into my javascript. The file I want to parse is contact.xml, located in my root folder.
Again, thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
<title>Contacts</title>
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("contactinfo.xml") // Path to the XML file;
var M = xmlDoc.getElementsByTagName("item");
for (i=0;i<M.length;i++){
document.write("<div style='width:450px;'>")
document.write("<h2>"+xmlDoc.getElementsByTagName("item")[i].childNodes[0].nodeValue+"</h2>");
document.write("<p>" + xmlDoc.getElementsByTagName("servicephone")[i].childNodes[0].nodeValue+ "</p>");
document.write("<p><a href='" + xmlDoc.getElementsByTagName("email")[i].childNodes[0].nodeValue +"</p>);
document.write("</div>")
}
</script>
</body>
</html>
*Here is my .xml file*
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="(800) 500-0066"
email="customerservice#fsig.com"
url="http://www.fsig.com"
address="5000 Barcilona Beach Rd. Wilmington, NC 28000">
</item>
</Contacts>
You need to go down the hierarchy, so, first find the Contacts node, then inside there you can get all the tagnames as you have.
You have a great deal of attributes so you may find this useful also:
node.attributes["url"].nodeValue
So just loop through all the items, then I would just copy itemelem[t] to node just to make it easier, then you get the attributes you need.
Depending on the browser you are using most of them come with some javascript debugger, so you can put in breakpoints and look at the values in the variables and see what the next step needs to be.
Friends,
I am trying to use DyGraph in my application. Please look at the code below -
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
<title>crosshairs</title>
<script type="text/javascript" src="dygraph-combined.js"></script>
<script type="text/javascript" src="data.js"></script>
</head>
The code uses data.js file containing function to get some static data.
I want data.js to be generated using a controller method so that it will generate data using database.
Can anybody help me out to resolve this issue.
Thanks for sharing your valuable time.
You could define a controller action:
public ActionResult Data()
{
// Obviously this will be dynamically generated
var data = "alert('Hello World');";
return JavaScript(data);
}
and then:
<script type="text/javascript" src="<%= Url.Action("Data", "SomeController") %>"></script>
If you have some complex script that you don't want to generate in the controller you could follow the standard MVC pattern by defining a view model:
public class MyViewModel
{
... put required properties
}
a controller action which would populate this view model and pass it to the view:
public ActionResult Data()
{
MyViewModel model = ...
Response.ContentType = "application/javascript";
return PartialView(model);
}
and finally a view which in this case will be the javascript representation of the view model (~/Views/SomeController/Data.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" %>
alert(<%= new JavaScriptSerializer().Serialize(Model.Name) %>);
Full Disclosure
This answer is copy/pasted from another question:
Dynamically generated Javascript, CSS in ASP.NET MVC
This answer is similar to other answers here.
This answer uses cshtml pages rather than ascx controls.
This answer offers a View-Only solution rather than a Controller-Only solution.
I don't think my answer is 'better' but I think it might be easier for some.
Dynamic CSS in a CSHTML File
I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:
/*<style type="text/css">/* */
CSS GOES HERE
#{return;}</style>
Dynamic JS in a CSHTML File
I use JavaScript comments // to comment out a new <script> tag and then I return; before the closing script tag:
//<script type="text/javascript">
JAVASCRIPT GOES HERE
#{return;}</script>
MyDynamicCss.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
}
/*<style type="text/css">/* */
#foreach (var field in fieldList) {<text>
input[name="#field"]
, select[name="#field"]
{
background-color: #bbb;
color: #6f6f6f;
}
</text>}
#{return;}</style>
MyDynamicJavsScript.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);
}
//<script type="text/javascript">
$(document).ready(function () {
var fieldList = "#Html.Raw(fieldArray)";
var fieldArray = fieldList.split(',');
var arrayLength = fieldArray.length;
var selector = '';
for (var i = 0; i < arrayLength; i++) {
var field = fieldArray[i];
selector += (selector == '' ? '' : ',')
+ 'input[name="' + field + '"]'
+ ',select[name="' + field + '"]';
}
$(selector).attr('disabled', 'disabled');
$(selector).addClass('disabled');
});
#{return;}</script>
No Controller Required (using Views/Shared)
I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:
<style type="text/css">#Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">#Html.Partial("MyDynamicJavaScript")</script>
Using a Controller (optional)
If you prefer you may create a controller e.g.
<link rel="stylesheet" type="text/css" href="#Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="#Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>
Here's what the controller might look like
MyDynamicCodeController.cs (optional)
[HttpGet]
public ActionResult MyDynamicCss()
{
Response.ContentType = "text/css";
return View();
}
[HttpGet]
public ActionResult MyDynamicJavaScript()
{
Response.ContentType = "application/javascript";
return View();
}
Notes
The controller version is not tested. I just typed that off the top of my head.
After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml #{return;}, but I haven't tried it. I imagine it's a matter of preference.
Concerning my entire answer, if you find any syntax errors or improvements please let me know.