I would like to use mustache.js with jQuery in my HTML5 app, but I can't make all the component work together. Every file is found, there is no problem here (the template is loaded roght, I can see its value in the Firebug debugguer).
Here is my index.html :
<!DOCTYPE html>
<html lang="fr">
<head><meta charset="utf-8"></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="../js/jquery.mustache.js"></script>
<script src="../js/app.js"></script>
<div id="content"></div>
</body>
</html>
Here is my app.js file :
$(document).ready(function() {
var template = $.get('../templates/article.mustache');
$.getJSON('../js/article.json', function(view) {
var html = Mustache.to_html(template, view);
$("#content").append(html);
});
});
The jquery.mustache.js file is the one generated from https://github.com/janl/mustache.js :
/*
Shameless port of a shameless port
#defunkt => #janl => #aq
See http://github.com/defunkt/mustache for more info.
*/
;(function($) {
// <snip> mustache.js code
$.mustache = function(template, view, partials) {
return Mustache.to_html(template, view, partials);
};
})(jQuery);
Noting is displayed. Firebug tells me
Mustache is not defined
See capture :
I know something is missing, but I can't tell what.
Thanks.
EDIT:
The correct and complete answer to a minimal example is the following :
write the template in the script, do not load it from a file
idem for the json data
read how the jQuery is generated and use $.mustache.to_html function instead of the (documented on github) Mustache.to_html (thanks to #mikez302)
refactor 'till you drop
$(document).ready(function() {
var template = " ... {{title}} ... ";
var json = {title: "titre article" }
var article = $.mustache(template, json);
$("#content").append(article);
});
But, it is easy to read the json from another file :
$(document).ready(function() {
var template = " ... {{title}} ... ";
$.getJSON('../js/article.json', function(view) {
var article = $.mustache(template, view);
$("#content").append(article);
});
});
You can finally also read the template from a file :
$(document).ready(function() {
$.getJSON('../js/article.json', function(view) {
$.get("../templates/article.mustache", function(template) {
var article = $.mustache(template, view);
$("#content").append(article);
});
});
});
Working example (without loading order problems) :
$(document).ready(function() {
$.getJSON('../js/article.json', function(model) { return onJSON(model); });
});
function onJSON(model) {
$.get("../templates/article.mustache", function(view) {
var article = $.mustache(view, model);
$("#content").append(article);
});
}
In place of Mustache.to_html, try $.mustache. It looks to me like the Mustache variable is defined within the function, so it is not directly accessible outside of it.
I know this question already ahs been answered, however I wrote a blog post on precisely this topic and thought I would share it here so anyone looking for examples of how to use Mustache with jQuery might see it.
http://blog.xoundboy.com/?p=535
Related
I am new to web development, so I am taking a Pluralsight course called "Building a Web App with ASP.NET Core RC1, MVC 6, EF7 & AngularJS" by Shawn Wildermuth. In his jQuery module, Shawn has this piece of code that works flawlessly for him:
var main = $("#main");
main.on("mouseenter", function() {
main.style = "background-color: #888;";
});
main.on("mouseleave", function() {
main.style = "";
});
I have a div with id="main" on my index.html page, js file is referenced, other jQuery functionality in the same file works, I just can't get this piece of code to work. I know it is not significant, but at this point it is personal. Any suggestions are helpful. Thank you!
As style is a property of native DOM element and main is a jQuery object. You can use .css() and .removeAttr() jQuery method to get the desired result.
var main = $("#main");
main.on("mouseenter", function() {
main.css("background-color": "#888");
});
main.on("mouseleave", function() {
main.removeAttr('style');
});
You can't access the style property like this. Try the following:
var main = $("#main");
main.mouseenter(function() {
main.css("background-color", "#888");
});
main.mouseleave(function() {
main.css("background-color", "none");
});
Try this:
var main = document.getElementById("main");
main.onmouseenter=function(){
main.setAttribute('style', 'background-color:#888;');
};
main.onmouseleave=function(){
main.removeAttribute("style")
};
I'm trying to make a web app that allows (student) users to see all possible class schedules that they can have. Right now, I've got a list of classes that fit certain constraints (users desired classes). I want to create all possible schedules that can be made with combinations of these classes. It seems like FullCalendar might be what I want to display these schedules (just in a week view or something) but i'm not sure if I can make FullCalendar just display a possible schedule and then allow the user to click through the possible schedules without assigning all the classes dates or something on the back end.
In a nutshell:
Is FullCalendar what I want to use for this? Or is there something else better suited to my goal?
Below is the code I have so far (still figuring out how to get lists of all possible schedules from this list)
<!DOCTYPE html>
<html>
<head>
<script src='../lib/jquery.min.js'></script>
<script src='../lib/jquery-ui.custom.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h2 id="search_results"></h2>
<div id="morning_results_container">
<h5>Morning Courses</h5>
<ul id="morning_results_list">
</ul>
</div>
<script>
$(document).ready(function() {
$.getJSON("http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS", function(result) {
var earlyCourses = [];
$(result).each(function (index, item) {
$('#search_results').text((index+1) + " total courses");
if (item.start_time > '10:00:00') {
if (item.meeting_days === 'We'){
console.log(item);
$('#morning_results_list').append('<li>' + item.title + '</li>');
}
}
});
});
});
</script>
</head>
<body>
<div id="resultarea"></div>
</body>
</html>
Thanks for any experiential advice you can offer!
Yes, I think you can achieve what you like to do with jquery FullCalendar plugin you are using. I'm not sure whether there is a better plugin for your purpose. FullCalendar pretty much provides a very good user interface for a interactive calendar for any type of web app.
However it's up to you to implement what it should do in your web app based on the UI interactions of a user. Could you provide a example of a JSON output with all the schedules? As I understood your question, maybe you can allow the user to select a schedule from a drop-down list and then show the classes in the calendar for a selected schedule.
[Update]
function load_all_classes()
{
$.getJSON("http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS", function(data) {
window.all_classes = data;
});
}
function update_calendar(classes)
{
//update calendar to display the given classes
}
function get_classes_before_10_am()
{
var results = [];
$(window.all_classes).each(function (index, the_class) {
if (the_class.start_time <= '10:00:00') {
results.push(the_class);
}
});
return results;
}
$(document).ready(function() {
load_all_classes();
$('#select_schedule').change(function(){
if ($(this).val = 'Before 10 am')
{
update_calendar(get_classes_before_10_am());
}
else if ($(this).val = 'After 10 am')
{
update_calendar(get_classes_after_10_am());
}
//...etc
});
});
I am attempting to create a modal dialog in sharepoint 2010, but I'm getting this error:
TypeError: this.$E_0.getElementsByTagName is not a function
my code is:
var options = SP.UI.$create_DialogOptions();
options.html = '<div class="ExternalClass23FFBC76391C4EA5A86FC05D3D9A1904"><p>RedConnect is now available.</p></div>';
options.width = 700;
options.height = 700;
SP.UI.ModalDialog.showModalDialog(options);
using firebug, i tried simply using the url field instead of the html field and it gave no error.
also related to this, what does SP.UI.$create_DialogOptions() actually do? what is the difference between using it and simply using a dict of values for your options?
options.html requires a HTML DOM element instead of plain HTML code:
<script>
function ShowDialog()
{
var htmlElement = document.createElement('p');
var helloWorldNode = document.createTextNode('Hello world!');
htmlElement.appendChild(helloWorldNode);
var options = {
html: htmlElement,
autoSize:true,
allowMaximize:true,
title: 'Test dialog',
showClose: true,
};
var dialog = SP.UI.ModalDialog.showModalDialog(options);
}
</script>
Boo
Example code taken from the blog post Rendering html in a SharePoint Dialog requires a DOM element and not a String.
also related to this, what does SP.UI.$create_DialogOptions() actually do? what is the difference between using it and simply using a dict of values for your options
When you look at the definition of the SP.UI.DialogOptions "class" in the file SP.UI.Dialog.debug.js you see that its a empty javascript function.
SP.UI.DialogOptions = function() {}
SP.UI.$create_DialogOptions = function() {ULSTYE:;
return new SP.UI.DialogOptions();
}
My guess is that it is there for client diagnostic purpose. Take a look at this SO question: What does this Javascript code do?
I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:
var context = {
name: this.model.get('name'),
email: this.model.get('email')
}
var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";
var html = Mustache.to_html(template, context);
$(this.el).html(html);
$('#app').html(this.el);
I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.
Tips?
Updated (4/11/14):
As answered by OP below:
Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender
Original Answer:
I just used this a couple of hours ago:
http://api.jquery.com/category/plugins/templates/
It's an official jQuery plugin(i.e. the devs endorse it).
This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/
Here's the code to have a template in HTML:
<script id="titleTemplate" type="text/x-jquery-tmpl">
<li>${Name}</li>
</script>
___________
// Compile the inline template as a named template
$( "#titleTemplate" ).template( "summaryTemplate" );
function renderList() {
// Render the movies data using the named template: "summaryTemplate"
$.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
}
It's in a <script> tag, because that's not visible by default.
Note the type="text/x-jquery-tmpl". If you omit that, it will try to parse it as JavaScript(and fail horribly).
Also note that "loading from a different file" is essentially the same as "reading a file" and then "loading from a string".
Edit
I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl
I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)
var TEMPLATES = {};
var Template = {
load: function(url, fn) {
if(!TEMPLATES.hasOwnProperty(url)) {
$.ajax({
url: url,
success: function(data) {
TEMPLATES[url] = data;
fn(data);
}
});
} else {
fn(TEMPLATES[url]);
}
},
render: function(tmpl, context) {
// Apply context to template string here
// using library such as underscore.js or mustache.js
}
};
You would then use this code as follows, handling the template data via callback:
Template.load('/path/to/template/file', function(tmpl) {
var output = Template.render(tmpl, { 'myVar': 'some value' });
});
We are using jqote2 with backbone because it's faster than jQuery's, as you say there are many :)
We have all our templates in a single tpl file, we bind to our template_rendered so we can add jquery events etc etc
App.Helpers.Templates = function() {
var loaded = false;
var templates = {};
function embed(template_id, parameters) {
return $.jqote(templates[template_id], parameters);
}
function render(template_id, element, parameters) {
var render_template = function(e) {
var r = embed(template_id, parameters);
$(element).html(r);
$(element).trigger("template_rendered");
$(document).unbind(e);
};
if (loaded) {
render_template();
} else {
$(document).bind("templates_ready", render_template);
}
}
function load_templates() {
$.get('/javascripts/backbone/views/templates/templates.tpl', function(doc) {
var tpls = $(doc).filter('script');
tpls.each(function() {
templates[this.id] = $.jqotec(this);
});
loaded = true;
$(document).trigger("templates_ready");
});
}
load_templates();
return {
render: render,
embed: embed
};
}();
They look like
<script id="table" data-comment="generated!!!!! to change please change table.tpl">
<![CDATA[
]]>
</script>
I have a dojo dijit.Tree, and I want to be able to put some html in the labels. To do this, I created an function called getCustomLabel and assigned it to the tree getLabel attribute:
tree = new dijit.Tree({
model: aMOdel,
showRoot: false,
getLabel: getCustomLabel
});
function getCustomLabel(item) {
return '<b>'+item.name+'</b>'
}
This returns a Tree with the html escaped so that it displays in the tree. Does anyone know of a way to get unescaped html in a tree widget?
There is a very simple way actually :)
Right after the dojo.require statement add the following:
dojo.require("dijit.Tree");
dijit._TreeNode.prototype.setLabelNode = function (label) {
this.labelNode.innerHTML = label;
};
With dojo release 1.7.1 the following works:
dojo.require("dijit.Tree");
dijit._TreeNode.prototype._setLabelAttr = {node: "labelNode", type: "innerHTML"};
Wouldn't unescape() achieve this?
function getCustomLabel(item) {
item.name = unescape(item.name);
return '<b>'+item.name+'</b>';
}
you can use onClick event and redirect page to that addess:
<div dojotype="dijit.Tree" model="model" id="tree" >
<script type="dojo/method" event="onClick" args="item,treeNode">
window.location = "/Default.aspx?ItemId=" + dataStore.getIdentity(item);
</script>
</div>
If you just want to print your label in bold, you can redefine getLabelStyle function of your dijit/Tree.
For instance:
getLabelStyle: function(item) {
return {'font-weight': 'bold'};
}