开发者

JavaScript Templating Engine

开发者 https://www.devze.com 2022-12-27 02:15 出处:网络
I would like to create universal templating engine in JavaScript, how to? HTML template <h1>开发者_开发技巧;<%title1%></h1>

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

0

精彩评论

暂无评论...
验证码 换一张
取 消