I used to use mustache.js for my templates on a quickbase app, but recently decided to switch over to trying handlebars so that I could use the if/then of it for a more appealing template.
However I can not seem to get them to work like mustache did, the Get for my module.js shows in the console, but after that the page doesn't load like it's supposed to (it usually loads the template.html)
module.js
var dbidApplication = "dbidHere";
var dbidTable = "dbidtHere";
var apptoken = "apptokenhere";
$.ajaxSetup({
data: {
apptoken: apptoken
}
});
var promise1 = $.get(dbidApplication, {
a: "dbpage",
pagename: "template.html"
});
var promise2 = $.get(dbidTable, {
act: "API_GenResultsTable",
query: "{3.EX." + kRid + "}",
jsa: 1,
options: "num-1",
});
$.when(promise1, promise2).then(function(html, data) {
//do some stuff with all the data
var template = Handlebars.compile(html[0]);
console.log(html[0]);
console.log(data[0]);
console.log(qdb_data);
$(template(qdb_data)).appendTo("#external");
});
My template has the source for handlebars and the div with id external
template.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.runtime.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div id="external"></div>
</body>
</html>
I think you forgot to set qdb_data:
$.when(promise1, promise2).then(function(html, data) {
//do some stuff with all the data
var template = Handlebars.compile(html[0]);
var qdb_data = data[0];
console.log(html[0]);
console.log(data[0]);
console.log(qdb_data);
$(template(qdb_data)).appendTo("#external");
});
Related
I am building a simple chrome extension using HTML and js which
Takes URL of the current page
Converts it to google search string
Display links of all the results on the first page as an unordered list in the extension box.
I am stuck on the 3rd step.
I understand that this may be done using Beautiful Soup in Python but don't know how to implement it using JS.
On doing console.log(html), I am getting an empty string, but the same code works on any other html page.
HTML code -
<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<h1>Top 5 searches from google</h1>
<button id="checkPage">Click!</button>
<ul>
</ul>
</body>
</html>
JS code -
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let myUrl = 'https://www.google.com/search?q='+tabs[0].url;
fetch(myUrl, {mode: 'no-cors'}).then(function (response) {
console.log(response)
console.log(response.text())
return response.text();
}).then(function (html) {
console.log(html)
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
console.log(doc)
var h3Elements = doc.getElementsByTagName("h3");
console.log(h3Elements);
}).catch(function (err) {
console.warn('Something went wrong.', err);
});
});
}, false);
}, false);
Im trying to call a function from another js file that is located in the same application directory as my main js script and html file. I receive an error claiming that the referenced function does not exist. I have referenced both of the scripts in the main html file in the proper order but cant for the life of me figure out why it cannot detect the function. I can only assume it has something to do with how dojo parses through the files and have experimented with both its dojo/domReady! and dojo/ready modules in hopes to force scripts to load. I feel like this should be much simpler than Im making it out to be. Any help would be greatly appreciated.
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Asset View</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
<link rel="stylesheet" href= "styles/styles.css">
<script src="http://js.arcgis.com/3.14/"></script>
<script src="scripts/requests-js.js"></script>
<script src="scripts/layout-js.js"></script>
<script src="scripts/xmain-js.js"></script>
</head>
<body class = "claro">
</body>
</html>
requests-js.js
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function() {
console.log("request start");
function sendRequest (url,assetCode,fromDate,toDate) {
console.log("Request innit");
request(url,{
method: "POST",
handleAs: "json",
headers: {"Content-Type": "application/json"},
data: JSON.stringify(
[
{
"AssetCodes": assetCode,
"FromGasDay": fromDate,
"ToGasDate": toDate
}
]
)
}).then(function(resp){
console.log(JSON.stringify(resp));
var naStorageJSON = resp;
});
}
console.log("request end");
});
});
main-js.js
require([
"dojo/dom","dojo/on","dojo/parser","dojo/json","dojo/request","dojo/ready"
], function(dom,on,parser,JSON,request,ready) {
ready(function() {
console.log("Main Start");
var url = "http://*********";
var assetCode = ["**"];
var toDate = "****";
var fromDate ="*****";
on(dom.byId("senecaLakeBtn"),"click", sendRequest(url,assetCode,toDate,fromDate));
console.log("Main End");
});
});
The issue is scope here. By declaring an empty array at the top of the js script (outside of its successive functions) the function can be accessible to other scripts in the application.
var app = [];
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function(){
app.sendRequest = function sendRequest (url,assetCode,fromDate,toDate) {
...
...
}
}
it can them be called upon from other scripts by referencing
app.sendRequest(arg1,arg2,arg3);
I'm trying to build a basic JQuery app which loads images from Flickr, adds them to an array of jQuery objects, sequentially adds them to the DOM, fades them in, and fades them out in a 3 second cycle. However, in my displayImage function, I cannot use .hide(), .fadeIn() or .fadeOut() because it throws an 'Uncaught TypeError: Cannot read property 'fadeIn' of undefined' error. Here is my code, both the JS and the HTML:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
//Creates the empty array of jQuery image objects
var images = [];
$.getJSON(url, function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
//Populates the images array with jQuery objects defined from the Flickr JSON request
images.push($img);
// $("main .photos").append($img);
// $img.fadeIn();
});
});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
//Function which recursively calls 'displayImage' every three seconds
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
And
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flickr App</title>
<link rel="stylesheet" type="text/css" href="stylesheets/styles.css">
</head>
<body>
<header>
</header>
<main>
<div class = "photos">
</div>
</main>
<footer>
</footer>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/app.js"></script>
</body>
Any ideas what might be undefined? Note that the var $img = $("<img>").hide(); line in the $.getJSONrequest doesn't throw the undefined error!
Thanks very much!
EDIT:
I've also tried to make a synchronous request to fetch the JSON, to make sure it's loaded before the displayImage function is called, and still it throws the same errors:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
var images = [];
//THIS IS WHAT HAS CHANGED
$.ajax({url: url,
dataType: 'json',
async: false,
success: function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
images.push($img);
});
}});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
You need to wait for the JSON to return before you try to displayImage(0). The JSON request is asynchronous, so your call to displayImage is happening before any JSON has been returned.
I recommend stepping through with a Javascript debugger to better understand what’s going on. You would see then that images is empty, and therefore $displayedImg is undefined.
I can't for the life of me figure out what I'm doing wrong.
This is my HTML/JS:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="handlebars-v1.1.2.js"></script>
<script>
$(document).ready(function(){
var jsonString = null;
$.getJSON("data.json", function(data) {
jsonString = data;
});
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
});
</script>
</head>
<body>
<script id="items" type="text/x-handlebars-template">
<span>{{Title}} : {{CSCI}}</span>
</script>
<ul>
</ul>
</body>
</html>
And this is my data.json file:
{
"Title":"I am a thing",
"CSCI":" "
}
The only output I get is the ":" so it's doing something properly. The console shows nothing (as in completely empty so I assume there's no syntactical errors anywhere?).
I don't like posting questions like this as it's usually because of a small mistake on my part somewhere, but I know you guys love this stuff ;)
As getJSON is an async function call you need to compile Handlebars in success callback function
$(document).ready(function(){
var jsonString = null;
$.getJSON("data.json", function(data) {
jsonString = data;
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
});
});
getJSON is async, and so
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
should all be inside of the callback as well
For jQuery template:
http://api.jquery.com/category/plugins/templates/
I want to be able to dynamically load the templates from a server, rather than predefining it on the page.
The demos I saw on the projects are using predefined templates. After some research I found out that it is possible.
I try doing this and it doesn't work:
<script src="child.html" type="text/x-jquery-tmpl"></script>
I tried doing this and it doesn't work:
$(function () {
$.get("child.html", function (data) {
//Add template
$.template("tmplChild", data);
});
//template binds before async call is done
$.tmpl("tmplChild").appendTo("body");
});
And finally, I have get it down to the following hack:
so.html (This is the main page):
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script type="text/javascript" src="so.js"></script>
<script type="text/javascript">
$(function () {
initTemplates(templateReady);
});
function templateReady() {
$.tmpl("tmplChild").appendTo("body");
}
</script>
</body>
</html>
child.html (This is the child template)
<h1>Child Loaded</h1>
so.js (This is my hack for ajaxly loading the js templates)
function initTemplates(callback) {
var templateUrl = "child.html";
var templateName = "tmplChild";
initTemplate(templateUrl, templateName, callback);
}
function initTemplate(url, name, callback) {
var opts =
{
type: "GET",
url: url,
dataType: ($.browser.msie) ? "text" : "xml",
success: function (data) {
xmlCallback(data, name, callback);
},
error: function (x) {
xmlCallback(x.responseText, name, callback);
}
}
$.ajax(opts);
}
function xmlCallback(data, name, callback) {
if (typeof data != "string") {
if (window.ActiveXObject) {
var str = data.xml;
data = str;
}
// code for Mozilla, Firefox, Opera, etc.
else {
var str = (new XMLSerializer()).serializeToString(data);
data = str;
}
}
//only takes strings!
$.template(name, data);
callback();
}
And here's what I don't like about it.
This doesn't work on Chrome
It seems like a lot of code just to load some template
I lost the ability to use $(document).ready(). I must now put all my code in this templateReady() method to be "template safe".
Is there a way around this?
Thanks,
Chi
Just load the template body as simple text and forget about putting it in a dummy <script> block. You can use $.tmpl(body, params) to populate the template and turn it into a string for appending to the DOM.
The whole thing with "not really script" <script> blocks is just a convenience useful in some situations.
edit — example:
$.get("/some/url/for/a/template", function(templateBody) {
var expandedTemplate = $.tmpl(templateBody, { param1: 0, param2: "Hello World" });
});
If the goal is to fetch a unique template each time you get data via ajax, then you might try fetching the template at the same time and include it in your data, that is if you have the luxury of modifying the returned object (anonymous object in .Net). Then you can store the template anywhere you want and you only need 1 ajax call for both the data and the template.
Refer here:
https://www.npmjs.com/package/jlate
use CDN:
<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate#0.0.2/jlate/JLate.min.js"></script>
HTML Code:
<body>
<div>
<jlate id="my_temp" src="template/jlate_title.html" type="template">
Loading...
</jlate>
</div>
</body>
Javascript:
$$("#my_temp").jlate({ title: "sample title"});