简体   繁体   中英

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是很酷的解决方案

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM