Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

What good template language is supported in JavaScript?

Templates are a pretty healthy business in established programming languages, but are there any good ones that can be processed in JavaScript?

By "template" I mean a document that accepts a data object as input, inserts the data into some kind of serialized markup language, and outputs the markup. Well-known examples are JSP, the original PHP, XSLT.

By "good" I mean that it's declarative and easy for an HTML author to write, that it's robust, and that it's supported in other languages too. Something better than the options I know about. Some examples of "not good":


String math:

element.innerHTML = "<p>Name: " + data.name
    + "</p><p>Email: " + data.email + "</p>";

clearly too unwieldy, HTML structure not apparent.


XSLT:

<p><xsl:text>Name: </xsl:text><xsl:value-of select="//data/name"></p>
<p><xsl:text>Email: </xsl:text><xsl:value-of select="//data/email"></p>

// Structurally this works well, but let's face it, XSLT confuses HTML developers.


Trimpath:

<p>Name: ${data.name}</p><p>Email: ${data.email}</p>

// This is nice, but the processor is only supported in JavaScript, and the language is sort of primitive (http://code.google.com/p/trimpath/wiki/JavaScriptTemplateSyntax).


I'd love to see a subset of JSP or ASP or PHP ported to the browser, but I haven't found that.

What are people using these days in JavaScript for their templating?

Addendum 1 (2008)

After a few months there have been plenty of workable template languages posted here, but most of them aren't usable in any other language. Most of these templates couldn't be used outside a JavaScript engine.

The exception is Microsoft's -- you can process the same ASP either in the browser or in any other ASP engine. That has its own set of portability problems, since you're bound to Microsoft systems. I marked that as the answer, but am still interested in more portable solutions.

Addendum 2 (2020)

Dusting off this old question, it's ten years later, and Mustache is widely supported in dozens of languages. It is now the current answer, in case anyone is still reading this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

John Resig has a mini javascript templating engine at http://ejohn.org/blog/javascript-micro-templating/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...