i'm very new to Handlebar js. In every article about the HandleBar js there is a word called (mustache js). So,
1. What is the relation between Handllebar js and Mustache js?
2. Is it necessary to read mustache js before handlebar js?
3. What s advantage of HandleBar js over Mustache js?
Thanks.
Handlebars.js is a superset of Mustache.js. It offers all the same ability to insert JSON into templates plus additional abilities to do some basic if/then, etc. In general, I find it much easier to do templating with Handlebars.
Mustache is very much about not having any logic in your template at all. Every piece that gets inserted into it should be pre-chewed so there's no need for any logic. I find that to not at all be realistic.
Just realized that I didn't answer one of your questions. No, it is not necessary to read about Mustache before using Handlebars. The Handlebars documentation is sufficient on its own.
P.S. One of our favorite Handlebars features is "helpers" which allow you to create new keywords in the language for specific things (for example, we use one to format numbers and sometimes replace them with "N/A" for zero values).
P.P.S. A great way to try out Handlebars and see some templates in action (and also to play with your own templates and JSON) is http://www.tryhandlebarsjs.com/
According to this website (which also provides a benchmark between the two)
handlebars.js is a compiled mustache implementation with some additional
features
Related
Trying out backbone+express with Jade as default templating.
Following a tutorial here(Great tutorial)
Confusion:
Many tutorials about backbone uses underscore template or handlebar to compile and render view.
I was using Jade as default template engine. My question is if I am using Jade then do I have to use another templating like Handlebar or underscore. If not how can I achieve following in Jade
render: function() {
var template = $("#booktemplate").html();
var compiled = Handlebars.compile(template);
var html = compiled(this.model.attributes);
this.$el.html(html);
return this;
},
My assumption: I am thinking Jade and Handle bar both are templating system and can be used alternatively. Is it so?
Why not use both Jade & Handlebar? I dont want to use two different syntaxes
#{} from jade / {{}} from Handlebar
Using Jade on the browser is not really a simple task. Thing is Jade is built for server side and does not support browsers.
This is why you'll often see people using two templates engines (if they use Jade). Some others are just gonna use Handlebars or Underscore everywhere - this is easier because templates engine working in the browser should work on the server. The other way around is not always true though.
Point to be taken here is that before starting to use a template engine, make sure it supports the environment you wish to target. There's plenty of options in term of engine, and this site can help you find one fittings your need: http://garann.github.io/template-chooser/
If you're really like Jade, then, you can use a stack like Browserify and some middleware (Jadeify) to make it work after pre-compilation. But you need to buy into the browserify concept and accept to precompile everything, everytime. You can check this related question for more details: https://stackoverflow.com/a/6623561/1024223
I'm using underscore template engine for an backbone application. As of now I have over 15 templates in the <head>. Its getting hard to maintain. So far, most of the solutions I seen to manage templates ended up needing them to be js files. That's also a headache, I prefer them to be html files for editing purposes.
I took a look at requirejs and not sure if I need that since it kinda revolves around a more modular approach that I can't say I'm using at the moment (although I will soon).
What will be the best way to manage templates and load/cache them as needed?
Personally we needed a robust solution at my company, so we went with:
Require.js - for module loading
Handlebars - for more powerful templating than Underscore can offer
HBS - an excellent require plug-in from Alex Sexton that handles bringing compiled templates in via Require
With this setup I can keep all of my templates in their own file, and then to use them I have files like this:
define(['template!path/to/someTemplate'], function(someTemplate) {
var MyNewView = BaseView.extend({template: someTemplate});
$('body').append(new MyNewView().render().el);
}
(and as you might guess we have a base Backbone view called BaseView which uses the view's template property to render the view).
Now, all that being said, if you don't need such a robust setup then Require may not be for you. In that case I would do the following:
Put all of your templates in to one or more HTML files; wrap them in script tags, like so:
<script id="dummyTemplate" type='text/template'>
<span>I'm a template!</span>
</script>
Write some code on your server-side to include those HTML files in the main HTML file you send to the client
Write a function which takes a template ID, gets the text of that element, compiles it in to a template, and returns that template (maybe cache the compiled templates if you want ... of course, with Underscore templates I don't think you even need compiling, so you can skip all that).
Use your function to access your templates: $("#something").html(templateFunc('dummyTemplate').template())
This will allow you to store your templates in html files (for syntax coloring), but still access them conveniently in JS. You can also divide your templates between as many files as you want, as long as you can write include logic to bring them in.
If you do opt for Require though, definitely check out the HBS plugin. And if you haven't looked at Handlebars templates yet, you might want to; they're far more powerful than Underscore ones (but like any good templating system, don't allow for too much logic).
Not sure what you mean by it being unmaintainable. Is it just a long list?
You don't need to keep your templates in the head. They can be at the bottom of your body as well. They just need to be defined before you try to use them.
One thing you might look into, depending on the server technology you are using would be to separate your templates into a different HTML file and include it at runtime.
My translation mechanism works serverside with the jinja2 template engine, webapp2's i18n function with the magic _ function and now I need it for Javascript to localize just a few strings but I couldn't find a good implementation. Is there one?
I'd like a solution for localizing my web app. The javascript strings are just a few but I need a translation mechanism and the dictionary is .po and .mo files. Ideally I'd like javascript to take the same dictionaries as python does (the .po files)
I don't need extractions, what I need is the _ function plus some way of determining user language and loading the translations, not just for a single language but for all my languages. I looked at some solutions but they only handla one translation at a time and I need to handle many.
For instance, http://www.zomeoff.com/jsin/jsin.1.2.unit.test.html does a successful job but this is only one localization. I need to harmonize the translations so that the same language is used by both the python jinja2 templates and javascript.
Do you have s suggestion or can comment my situation?
Thank yo
Javascript Gettext
You could probably use polib and json to generate the JSON on the fly though.
Update: after another day of digging
into this issue, I have found that the
current jQuery template lib provides
no way to do this. this article
describes a good approach.
I would still like to hear of any
additional thoughts on doing this. The
article linked above requires that the
returned string of templates be
inserted into the DOM. Seems as though
leaving the DOM out of this would be
ideal, and less overhead on the
browser. Imagine a large page, with
multiple composite templates that may
not get used. Although, maybe because
the templates are wrapped in a script
tag, there is only a single DOM item per template? Come on, let's
hear some thoughts...
Using jQuery template libs, what's the best way to combine multiple, related, relatively small templates together? Do you need a single <script> tag for each individual template? What about in the case of dynamically pulling these templates via AJAX? Can I combine these templates somehow?
Consider the following:
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl "#titleTemplate"}}
<tr class="detail"><td>Director: ${Director}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${Name}</td></tr>
</script>
Now because these two templates are very closely related (and one depends on the other) it would make sense to consolidate these into a single AJAX call, and get them both at once. I have a few ideas, but I'd like to know if there is common/best way to do this? Currently I pull in a chunk of HTML, and then do a .find() to get the specific peice of HTML for a template... e.g.:
var templatePackage = fancyAjaxCalltoGetTemplates();
"templatePackage" might then look like this:
<div id="templatePkg">
<div id="movieTemplate">
{{tmpl "#titleTemplate"}}
<tr class="detail"><td>Director: ${Director}</td></tr>
</div>
<div id="titleTemplate">
<tr class="title"><td>${Name}</td></tr>
</div>
</div>
I could then do:
var titleTemplate = jQuery.template('titleTemplate', $(templatePackage).find('#titleTemplate') );
and
var movieTemplate = jQuery.template('movieTemplate', $(templatePackage).find('#movieTemplate') );
...let me know what you think... what would you do?
I like the referenced article in your update, except the assumption that you can't cache templates unless you insert them into the DOM. From the jQuery.tmpl documentation,
"To cache the template when using markup that is obtained from a string (rather than from inline markup in the page), use $.template( name, markup ) to create a named template for reuse. See jQuery.template()."
Using this, we can build a javascript template management system that allows us to load as many templates at a time as we need while keeping the DOM clean. On the client, keep a hash of template objects by name. You can use your favorite object based javascript pattern here, but I would think the structure could be like this:
templates[templateName] = {
templateMarkup: markupFromServer,
loadedAt: Date.now(),
compiledTemplateFunction: jQuery.template( templateName, markupFromServer )
}
Then use the templates to generate HTML like this:
templates['unique-name'].compiledTemplateFunction(inputData)
Then, build an unload mechanism to free up memory:
function unload(templateName) {
delete templates[templateName];
delete jquery.template[templateName];
}
Most importantly, you now have a method of storing multiple templates so you can make requests like: $.get('/TemplateManagement/Render', arrayOfTemplateNamesToLoad, loadManyTemplatesSuccess) to load multiple templates at a time. The only thing we need is a controller TemplateManagement that will take an array of template names as an input and return JSON that pairs a template name with its markup. There are a few ways to do this but it seems to me the most convenient is to define partial views for each template. In ASP.NET MVC 3, you can use this technique and RenderPartial to emit each template's markup into a JSON response. You can either name the partial views the same as the templates or map the names in some custom way.
OK, I read the article you reference in this post. As I see it, his way is probably one of the best ways to load up the template page(s). The only thing I don't like is the asynchronous problems that could crop up, esp. if you need to immediately do some templating before the async get returns... plus any binding issues that could happen before it returns something. In several projects I have done I use his "ancient" SSI (server side includes), but I just use something even easier like:
<% Response.WriteFile("this_page_template_file.html"); %>
You could put it anywhere where you'd place a tag. Like he says, just put in only the templates you need, or maybe include two templates: one is a "base" template with commonly-used items and the second one would have the page-specific ones with template references {{tmpl}}.
Is this even close to an answer? ;-)
[First off, great question. I love this topic]
I have no experience with the plugin "jquery-template-libs", but there is a particular lightweight javascript template plugins that are becoming almost a standard and plays very nicely with jQuery, which is probably better suited for the task than JTL, Mustache:
https://github.com/janl/mustache.js
It's got something that's called a "partial" which is essentially a way to include smaller templates within another one. Which sounds like it will help you out a lot.
On top of that there is a library called ICanHaz.js:
http://icanhazjs.com/
ICanHaz essentially extends Mustache to include built in functionality for templates and works incredibly well.
Mustache/ICanHaz allow you to add templates by variable, by a json call or by using tags. The choice is yours.
I know this is an old question but you might want to take a look at Closure-Templates. They provide the kind of functionality you're after with the added advantage of being compiled into JavaScript at compile-time instead of at run-time in each user's browser.
If you do decide to look into using them then I'd suggest using plovr for building them.
Has anyone ever worked with a system of passing back say, some JSON data and using a javascript routine to generate the HTML to save on bandwidth?
What methods are there and are there any templating systems available?
Start with John Resig's JavaScript Micro-Templating.
Some like it, some hate it, but you can create templates of HTML in string form within your base application package (e.g., the js files included in the main page.)
var fooTemplate = "<div class='%div_class_parent%'>"+
"<div class='%div_class_child%'/>"+
"</div>";
then you just load that into an existing DOM node using the innerHTML method.
document.getElementById('someNode').innerHTML = parseFooTemplate();
where parseFooTemplate returns fooTemplate with the %% elements replaced with correct data that was returned from the JSON.
This is just one of many ways to go about it. The dojo toolkit has their own way where widgets can have a HTML template behind the scenes. There's too many ways to enumerate here.
To generate HTML basing on JSON you will need some template engine for javascript
I would reccomend Zparse template engine http://code.riiv.net/zparse/ it is really great - i using it a lot.
The best part - you can extend it easily by declaring your own tags.