tags:

views:

111

answers:

3

Hi,

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!

+5  A: 

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).

M4N
Yay! This is excatly, what I was loking for! AJAX templates...
Randy Gurment
A: 

John Resig Micro-Templating is cool solution

Lauri
Thanks! Great!!
Randy Gurment
A: 

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

aefxx