Good Javascript template engine to work with JSON - javascript

I have looked at jTemplates and it's worth a try. Are there any other template engines other than jTemplates?

Did you try pure.js ?
The main difference with the dozens of JS templating engines available is that PURE leaves the HTML totally separated from the JS logic. And it's pretty fast too.
However it is not the common <% ... %> kind of templating programming you may like.It has a pattern/declarative approach which has some similarity with XSLT (but without the pain...)

I liked the approach the JavaScriptMVC Frameworks Views take, especially because it uses JavaScript itself as the templating language. The framework is now based on jQuery and you can render your Model right into the views (Model supports JSON, JSONP, XML etc.).

Here is one implemented in jQuery for the Smarty templating language. http://www.balupton.com/sandbox/jquery-smarty/demo/
One impressive feature is the support for dynamic updates. So if you update a template variable, it will update anywhere in the template where that variable is used. Pretty nifty.
You can also hook into variable changes using a onchange event. So that is useful for say performing effects or AJAX when say the variable "page" changes ;-)

You can use this one: https://jocapc.github.io/jquery-view-engine/
It binds properties of JSON object into empty HTML template and match properties with elements by name, id, or class.
First, you would need to have plain HTML template in your page:
<div id="template">
<h1 id="Name"></h1>
<label>Description:</label>
<textarea name="Desc"></textarea>
<ul>
<li class="bind-Tags"></li>
</ul>
</div>
Then you need JS object that will be placed in template:
var data = { Name: "JOVN",
Desc: "The simplest view engine",
Tags: ["View engine", "JavaScript", "SPA"]
}
Finally just fill the view with the data object:
$("div#template").view(data);
Result is:
<div id="template">
<h1 id="Name">JOVN</h1>
<label>Description:</label>
<textarea name="Desc">The simplest view engine</textarea>
<ul>
<li class="bind-Tags">View engine</li>
<li class="bind-Tags">JavaScript</li>
<li class="bind-Tags">SPA</li>
</ul>
</div>
View engine will populate single fields or replicate array elements in template.

Yajet is a new one, spotting a syntax different from anything we've seen before. :-) It compiles the templates and it's blazing fast. It's browser and library-agnostic; there is a small jQuery wrapper for people who can't live without jQuery, but the engine itself is independent and can run in Rhino or V8 too.
It supports many directives that allow conditionals, loops, define reusable template components etc.

After having this question in 2017, it looks like JsRender and JsViews have emerged as the current official implementation of templating within the jQuery ecosystem (whilst not necessarily requiring jQuery):
JsRender is a light-weight but powerful templating engine, highly extensible, and optimized for high-performance rendering, without DOM dependency. It is designed for use in the browser or on Node.js, with or without jQuery.
JsRender and JsViews together provide the next-generation implementation of the official jQuery plugins JQuery Templates, and JQuery Data Link -- and supersede those libraries.
- JsRender GitHub Readme
Official Site: http://www.jsviews.com/
GitHub (JsRender): https://github.com/BorisMoore/jsrender
GitHub (JsViews): https://github.com/BorisMoore/jsviews

Try async-js-templates. Its fast because it does paralell requests that can be async.
It is shiped with maven.

Its worth looking at the following link.
https://github.com/nje/jquery/wiki/jquery-templates-proposal

Related

How to write algorithms/pseudo-code in HTML?

I'm used to writing algorithms in LaTeX while preparing my slides in Beamer but now I'm using an HTML presentation engine (shower) to prepare my slides. Are there any similar workflow/styles (css, javascript) to write algorithms
in HTML?
I believe that there are plenty of them, but you can check pseudocode.js.
Pseudocode.js enables JavaScript to typeset algorithms as beautifullly as LaTeX does.
You could check out MathJax, which renders LaTeX pretty nicely (at least insofar as math is concerned). I haven't done algorithms with it, though, so I can't say how well (or whether) it does them.
I think a lightweight solution like handlebars.js is a good choice here. You can create dynamic layouts such as:
{{#if isActive}}
<img src="star.gif" alt="Active">
{{else}}
<img src="cry.gif" alt="Inactive">
{{/if}}
If you want algorithms in your HTML like conditions or such. You can use templating engines like Jade or Handlebars.
Jade: https://www.npmjs.com/package/jade
Handlebars: http://handlebarsjs.com/

How to use javascript templating rather than raw HTML in javascript string?

I am creating a web app that requires me to render new elements on the page many, many times. It is getting out of hand for me to add HTML by putting it into a Javascript string. Mostly because it's hard to edit it especially when it spans multiple ways. What's the best solution for this? And what's the best way to organize this stuff because I feel like I am going to have a huge page full of JS "subelements".
There are a huge number of JavaScript templating engines available. Some of the more popular ones include:
Mustache
Handlebars
Underscore
jQuery.template
Most work by compiling your template text into a function that can be called with an object containing the data to be interpolated.
For example (using underscore.js):
var myTemplate = _.template("Hello <%= person %>");
alert(myTemplate({person : "egidra"}));
Here is a link about linked.in and templates.
I would use a js template engine. So no need to use html strings in the js. Look at the documentation of the templates. They all explain the use very well.
You can try something like http://handlebarsjs.com/ or http://mustache.github.com/.

When using (only) a templating system, how should I manage CSS, javascript etc for sub-templates?

I've had this same question when working with different templating systems in different languages in the past, so first,
The general question
I want to use a sub-template to include a certain UI component which might appear in different places on a number of different pages. This UI component requires certain CSS and JS files.
I want to Do The Right Thing with CSS and JS resources, which, as far as I know and in broad terms, is to a) combine as many as possible b) minify as much as possible and maybe c) put what I can at the end of my markup so the browser doesn't have to wait for them to load before displaying content.
So, if I've got various different UI components, as well as different headers and sidebars in different sections of the site, which all require their own special CSS and JS to function correctly, what's the best way for me to manage them through a templating system so that the final markup is as small and well-organised as possible?
Specifics of my situation
I'm working on a large legacy PHP site, on which, to give the original authors the benefit of the doubt, development may have begun before MVC became really mainstream, and before there were so many choices of frameworks around to use. So there is no consistent MVC framework, no routing, no templating (no ORM either, but that particular curse isn't as relevant here).
I'm going to have to keep things ticking over, squashing bugs and adding a few new features until a complete rewrite is usable, so I'm trying to breathe some sanity into things as I go along.
The easiest place to start seemed to be the views layer, for which I'm using TinyButStrong. An example of their sub-templates can be found here, but like I said, I think this is a very general question.
Things I've considered
With a more integrated framework I'd like to be able to do something like $view->add_js($foo), but transitioning to a full-blown framework is what other people are doing while I try keep the existing codebase seaworthy. There isn't even really enough consistent organisation of files to roll something like this by hand.
At the moment the best thing I can come up with is making a DOMDocument out of the view right before it's output and manipulating <link> and <script> tags at that point. I don't know if that's a bit crazy though. Given the generality of the problem I'd like to think that there's a known sensible way to go about it.
Many thanks for your input.
It's hard for the reader to know what can or cannot be done with your code base. A common way to handle this situation would be to pass parameters to the view template, and the template can then include conditional chunks or include sub-templates based on your parameters. This does not require a full-fledged framework, a stand-alone template engine should do. If your template engine supports inheritance there is a nice pattern for handling assets in your templates - check here for example http://symfony.com/doc/2.0/book/templating.html.
Manipulating the Dom for each request to handle this kind of thing seems bit unorthodox.
What you want in this situation is some form of template inheritance; that is, technology whereby a sub-template has access to areas in a 'parent' template, and can edit or replace content in those areas. Using this ability, CSS and JS required for a component included via a sub-template can be added in to the <head> element of the parent page.
In Twig, this is achieved using named blocks. First, you create your parent template (or layout, as it's called in Twig), e.g. index.html.twig. You include in it a named block like {% block myCss %}.
Next, to create a sub-template, you begin the template with the line {% extends ::index.html.twig %}. Then, the content of a block defined in the sub-template with the same name as a block in the parent template (in this case {% block myCSS %}) will get substituted into the parent template. To append rather than replace content in the parent template, use {{ parent() }} to include content already existing in the parent.
An example of this with code is available at the link given by #Basel Shishani. I've heard that Twig is modelled after Django, and template inheritance in Django looks very similar (with the exception of using {{ block.super }} instead of {{ parent() }}. There is a discussion of how to achieve the same ends in TinyButStrong.
As a wider point, the Assetic library looks like a very promising solution for managing CSS and JS assets, in order to avoid duplication (e.g. where the same JS file is required by multiple components/subtemplates), enable concatenation and minification of assets, and more. This presentation of its features gives more details.

Explanation of <script type = "text/template"> ... </script>

I just stumbled upon something I've never seen before. In the source of Backbone.js's example TODO application (Backbone TODO Example) they had their templates inside a <script type = "text/template"></script>, which contained code that looks like something out of PHP but with JavaScript tags.
Can someone explain this to me? Is this legit?
Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.
By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.
Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.
It's legit and very handy!
Try this:
<script id="hello" type="text/template">
Hello world
</script>
<script>
alert($('#hello').html());
</script>
Several Javascript templating libraries use this technique. Handlebars.js is a good example.
By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).
<script type="text/template">I am a Micro template.
I am going to make your web page faster.</script>
For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/
To add to Box9's answer:
Backbone.js is dependent on underscore.js, which itself implements John Resig's original microtemplates.
If you decide to use Backbone.js with Rails, be sure to check out the Jammit gem. It provides a very clean way to manage asset packaging for templates.
http://documentcloud.github.com/jammit/#jst
By default Jammit also uses JResig's microtemplates, but it also allows you to replace the templating engine.
It's a way of adding text to HTML without it being rendered or normalized.
It's no different than adding it like:
<textarea style="display:none"><span>{{name}}</span></textarea>
<script type = “text/template”> … </script> is obsolete. Use <template> tag instead.
jQuery Templates is an example of something that uses this method to store HTML that will not be rendered directly (that’s the whole point) inside other HTML:
http://api.jquery.com/jQuery.template/

JavaScript Templating Engine

I would like to create universal templating engine in JavaScript, how to?
HTML template
<h1><%title1%></h1>
<h2><%title2%></h2>
JSON file
{
"title1" : "Hello World!",
"title2" : "Hi World!"
}
Javascript
Find in HTML file <%title1%>
Find in JSON file variable "title1"
Replace <%title1%> with value of variable "title1"
Same for <%title2%>
Thanks!
Have a look at this article. It discusses a proposal (by microsoft) how support for templates could be added to the jQuery library.
In the same article you will also find an overview of some already existing template solutions (maybe you'll find something that matches your needs, instead of re-inventing the wheel).
Update (2012-07-23):
The jQuery templates project was abandoned more than a year ago. It seems that Boris Moore continues his work with the new projects jsrender and jsviews.
John Resig Micro-Templating is cool solution
You might want to have a look at my jQuery templating plugin jQote2. As far as usability and speed is concerned, I have yet to see a better templating solution (trust me, I've tried them all).
It has a built in closure compiler that let's you precompile your templates (handy if you want to keep your templates in .js files) and a caching mechanism. The current version also comes with a couple of convenient methods that ease the pain of appending/prepending/replacing DOM nodes.
Give it a try, you won't regret it.
Regards

Categories

Resources