JavaScript Templating Engine - javascript

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

Related

How to make the javascript code easy to maintenance

All, I am working on a highly interactive web application which will need a lot of jquery or js code, And I'm finding that my code is becoming a little hard to maintain and is not all that readable. Sometimes even the author can't find the specified code.
So far what I had done for the clear code is below.
One js component in one js file .(for example. CustomTab.js is a tab component in my app.)
Using the templete to generate component HTML based on JSON.
Using Jquery UI.
Unobtrusive JavaScript.
Is there any other points I need pay attention? Anyway, Any suggestion or recommend technique for making js library/framework easy to miantanance is appeciated, thanks.
I could suggest you to use module pattern together with RequireJS to organize your JavaScript code. For the production you'll be able to use RequireJS optimizer to build your modules into one JavaScript file.
Also if you're expecting that your client-side application will be huge, consider to use some JavaScript MVC framework like Backbone.js together with the server-side RESTful service.
I use this namespacing pattern for my libraries:
MyLibrary.ListView.js:
var MyLibrary = MyLibrary || {};
MyLibrary.ListView = {
doSomethingOnListView: function() {
...
return this;
},
doSpecialThing: function() {
...
return this;
},
init: function() {
// Additional methods to run for all pages
this.doSomethingOnListView();
return this;
}
};
Whichever page needs this:
<script type="text/javascript" src="/js/MyLibrary.ListView.js"></script>
<script type="text/javascript">
$(function() {
MyLibrary.ListView
.init()
.doSpecialThing();
});
</script>
You can even chain methods if a certain page requires an additional function.
This is exactly the same question which I ask myself each time. I think there are few ways to get easy maintaining code.
Contribute in javascript opensource projects and understand how they solved that problem. I think you can gather some unique solution from each project and common part of projects structure will answer to your question about maintenance.
Use prepared solutions like backbone, knockout, ember or angularjs if I am not mistaken angular doesn't give you structure but provide you powerful tool for creating pages with less code. Also check todomvc for ready-made solutions.
Read books and try to create some structure for your needs. It will be difficult and long but result (maybe few years later :)) will be awesome.
Currently I'm also working on a JS framework for my company. What I'm doing is I use OOP elements for JS. In other words I'm implementing similar code to C# libraries(not that similar, simulating will be the correct word). As an example in C# you use Microsoft.Window.Forms, so I can use JSOOP and use method extending and overriding to create the same scenario. But if you gone to far in your project converting your JS code to JSOOP will be time consuming.
use JSLint, this will validate your code and bring down to a readable, script engine friendly code. Though JSLint is very strict so you can use JSHint also.
using seperate file for each component is a good idea I'm doing it also.
If you like you can download the jQuery developers version and you can have a general idea how they created the framework. I learned lot of thing looking at jQuery framework!

Meaning of Dollar Sign & Curly Braces Containing Javascript Block Outside of HTML Script Tag

I'm currently reading 'Javascript Web Applications' (O'Reilly, Alex MacCaw) and very early on there's a code snippet which might appear to execute a JS function, within an HTML document, yet it is not enclosed by <script> tags:
// template.html
<div>
<script>
function doSomething(aParam) {
/* do stuff ... */
};
</script>
${ doSomething(this.someX) }
</div>
Please could someone kindly explain the dollar-sign-curly-brace notation? I'm currently learning JS and I haven't seen this before, so I'm presuming it's either JS shorthand for code execution (if so, why no terminating semi-colon?), or perhaps some proprietary templating mark-up (Ruby? PHP?), or something else entirely?
Many thanks.
UPDATE
It transpires that later on in Chapter 5 (of the aforementioned book) we are then introduced to Javascript templating. It appears to be an assumption by the author that the reader has already encountered this templating technique before reading the book. As noted by Stackoverflow member Esailija, this book is not a beginners' guide to Javascript; I should add that I'm reading this book in parallel with 'Javascript: The Good Parts' (O'Reilly, Douglas Crockford) amongst others.
I had half-suspected some kind of templating, but I hadn't considered pure JS templating. I have used PHP and RoR frameworks in the past which also used similar templating concepts for injecting model data into views.
One final point: my reason(s) for reading 'Javascript Web Applications' is that it discusses the Model-View-Controller (MVC) pattern within the JS sphere. While it advocates the use of the jQuery library (among others) to both enhance and accelerate development, it is not a jQuery API book or yet-another-new-javascript-wrapper; rather, the book makes use of such libraries (where appropriate) to deal with cross-browser JS inconsistencies, while driving home actual JS best practices and patterns in creating 'web applications'.
It's not supposed to be javascript but a template file. Template file contains static html and very dumb presentation logic, usually in a pseudolanguage as it is in this case. It should not contain any real javascript - as it is said in the book that it's something you shouldn't do.
The book then goes into a refactored version that only has static html and the pseudolanguage statement. See Javascript templating.
The book seems to be aimed at those who are already proficient at javascript and are looking into structuring their js better.

Django template implementation in javascript?

Does anyone know about an extensible django template implementation in javascript. I don't need all the advanced features, but loops, tags and filters would be nice.
I found a few projects/hacks just implementing the variable style but that's not enough for us.
The one that came closest is: http://code.google.com/p/jtl-javascript-template/ but it's not very well written/complete/maintained.
Check this : http://icanhazjs.com/
And here how it can work with django : http://tothinkornottothink.com/post/4282971041/using-jquery-templating-icanhaz-js-with-django
Another option is to use mustache.js and pystache. It would require some changes as the feature set isn't as powerful as Django templates but it does provide fair amount of freedom.

Good Javascript template engine to work with JSON

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

JavaScript libraries for Markdown, Textile and others; Anchor references

I need a javascript library to convert structured ascii text to html on the fly.
I am especially interested in the following point:
I would like do use anchored links inside pages, see http://www.w3.org/TR/REC-html40/struct/links.html#h-12.1.1
Which library for structured text would support this or if it is not supported could be easily extended (i could write an extension)?
Can you make a suggestion for a good and simple syntax for structured ascii text for "in page links"?
jump to the end
...some body text...
<a name="jumpend">this is the end</a>
I like the way links are written in "markdown", so how could the name anchor in a to be written extension be expressed in a nice way?
Which libraries do you know or can you recommend? Should be multi browser, good and easy to read and extend clean source code, actively maintained.
I am presently having a look at the JavaScript Markdown library "Showdown": http://attacklab.net/showdown/
You might look into markItUp!
I think that you should not use markdown if you are looking for anchor references. Try the following Creole Wiki markup parsers:
A prototype Javascript Creole 0.4 parser can be found at MeatballSociety
JavaScript Creole 1.0 Wiki Markup Parser, based on the above
Textile hast a builtin "footnote" mechanism:
.. AJAX[1] ...
fn1. Asynchronous JavaScript and XML ..
As of Textile 2.2 there's also a "notelist" feature: textile.sitemonks.com/?eg=notes

Categories

Resources