开发者

HTML Templates in Javascript? Without coding in the page?

I am a web guy doing mostly Perl server-side stuff, and I'm slowly coming to a few conclusions.

  • It is far better to do most of your code via Javascript and toss data back and forth via AJAX than it is t开发者_Go百科o hit submit and reload a mostly-identical page
  • I like jQuery because I like CSS, and it's fun to chain together big long and scary-to-others definitions
  • There's something to that templating stuff.

You want your HTML elements to look like your HTML elements, and it's easier to define that in HTML:

<div class="sidebar_elem">
     <a href=""> TEXT</a>
</div>

Than it is to cobble up the same in Javascript or jQuery:

( '<div/>' )
     .attr('id' , 'sidebar_elem' + i )
     .addclass( 'sidebar_elem' )
     ;
( '<a/>' )
     .attr('href' , link_url )
     .appendTo( '#sidebar_elem' + i )
     ;

This is to say that I am no longer a templating agnostic, but I don't know which templating tool to believe in. I have looked into some jQuery-based templating plugins, but I have yet to become happy with any of them, in part because the ones I've seen seem to want to put all that code into the page itself, which breaks the "Only markup goes into HTML files, only style goes into CSS files, only code goes into JS files" mantra I keep reciting.

So, I'm looking for a Javascript-based templating tool that would allow me to have my templates in an outside file so I can have one template change cover a series of web pages. If it's jQuery-based, that's great, less stuff I have to learn, but it isn't a deal-breaker.


There are several good ones out there:

Mustache.js
Pure.js
Json Template

If you want a jQuery version, Tempest looks good.


The 2 libs I know that do not mix template coding with HTML markups are chain.js and PURE

chain makes only DOM manipulations.
PURE uses a mix of DOM and innerHTML as the DOM alone can be slow to render bigger templates.

I'm the main contributor of PURE, and we created it to build a web app on the ajax model you describe.


Take a look at this one http://ejohn.org/blog/javascript-micro-templating/. Made by John Resig, creator of jQuery, this one doesn't even need jQuery, and it's freaking small. It also stores templates in script tag (Daniel's answer). Example template:

<script type="text/html" id="user_tmpl">
    <% for ( var i = 0; i < users.length; i++ ) { %>
        <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
    <% } %>
</script>

Maybe you can load them using src attribute if you really need them to be in separate files, which I don't think is a wise idea, because it means additional roundtrip to the server. So at the end, for the sake of optimization, you can store them in separate files, but embed them server side in the page that needs them.


Since there is no well defined API and a best library for templating, I would suggest you choose one that is actively developed. Below, I briefly explained two libraries that are actively being developed.

jQuery team decided that jQuery Templates will no longer be actively developed or maintained, thus I would strongly suggest NOT using it. See this blog entry.

You can use JsRender in accordance with JsViews to take full functionality provided by jQuery Templates and even more like data linking. You can find demos for JsRender and JsViews. I would suggest using these libraries since they are actively being developed by jQuery UI team but be aware that they are still not even beta!

Mustache is another templating solution that is actively being developed and it simplifies templates by combining conditional tags and enumeration tags. It also provides strong features like inverted sections, partials and high order sections with simple syntax. Mustache is also one of the fastest templating solutions See blog by Brian Landau. I, personally, find mustache a good templating solution since it has a simple syntax and performs well.


How about EJS?

Example from their page:

"EJS combines data and a template to produce HTML."

Data:

{title: 'Cleaning Supplies',  supplies: ['mop', 'broom', 'duster'] }

Template:

<ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>

Result:

  • mop
  • broom
  • duster


You should check out google closure template. It's completely independent so you can use it with any lib you want. It's a templating tool written in java.

http://code.google.com/closure/templates/docs/helloworld_js.html

It allows you to create a template on the server, run a java "compiler" on it and the output is a javascript function that takes json as its parameter.

{namespace examples}
/**
 * Greets a person using "Hello" by default.
 * @param name The name of the person.
 * @param? greetingWord Optional greeting word to use instead of "Hello".
 */
{template .helloName}
  {if not $greetingWord}
    Hello {$name}!
  {else}
    {$greetingWord} {$name}!
  {/if}
{/template}

This will generate a function called examples.helloName that can be called like

Their format is very IDE friendly, I get all the HTML syntax highlighting when editing the templates

examples.helloName({name: 'Ana', greetingWord:"Howdy"});

You can call other templates from within templates, it automatically html escapes your data (unless you tell it not to), provides bidirection support.

Another great thing is the fact that the templating tool can also generate java code. So somebody writing an app that must support browsers with scripting disabled can generate the HTML on the server if necessary.

Last but not least, unlike other js templating systems (), the template is parsed on the server, so the client side only has to do the merging of the template and data, the parsing of the template is done as a build step on the server.

http://dev.sencha.com/deploy/dev/docs/?class=Ext.XTemplate is an example of a templating tool that runs completely on the client. There are two problems with this approach, the parsing of the template is done on the client and your html has to be embedded in a javascript string. However, some IDEs (Intellij) will highlight the HTML inside JS strings).


What about JAML Code?

http://github.com/edspencer/jaml

Similar to a few of the above but I believe is a bit more logical...

It is the concept of defining your templates via JSON / JavaScript and then using a function in JavaScript to pass arguments to your template which gets it rendered and returned as an element.

There are implementations around for the various JavaScript Frameworks that exist.


Try out this: https://www.npmjs.com/package/jlate

use CDN:

<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate@0.0.2/jlate/JLate.min.js"></script>

I given below working example where you can replace github template url with your own template sample:

https://raw.githubusercontent.com/webphonix/JLate/main/test_project/template/weblate_loop.html

<div class="row">
  <% _.each(names, function(n){ %>
  <div class="col-md-6"><%- n.name %></div>
  <% }) %>
</div>

var author = [{
    name: "Guru"
  },
  {
    name: "Gurudev"
  },
  {
    name: "Test"
  },
  {
    name: "Webphonix"
  },
];
$$("#my_temp").jlate({
  names: author
});
<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate@0.0.2/jlate/JLate.min.js"></script>

<div>
  <jlate id="my_temp" src="https://raw.githubusercontent.com/webphonix/JLate/main/test_project/template/weblate_loop.html" type="template">
    Loading...
  </jlate>
</div>


Try JLate:

https://www.npmjs.com/package/jlate

use version 0.0.2 instead 0.0.1

use below cdn:

<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate@0.0.2/jlate/JLate.min.js"></script>


Use a script block.

<script id="someId" type="text/html">
   <!-- your template here -->
</script>

and one of many JQuery plugins.

http://weblogs.asp.net/scottgu/archive/2010/05/07/jquery-templates-and-data-linking-and-microsoft-contributing-to-jquery.aspx


I have a templating engine called stencil.js, which I believe is pretty sweet. It works with jQuery via the jquery-haml DOM building engine.

Write your template (which you can put in an external file and decode as JSON):

["%div.sidebar_elem"
    ["%a", { href: { key:'link' } },
        { key: "text" }
    ]
]

And run it through stencil along with your data:

$("#parent").stencil(template, { link: "http://example.com", text: "Click me!" });

There are more examples at the stencil.js GitHub project, but I think it's just what you're looking for.

It could use a couple more utility methods, and some code for an unfinished data binding component is still in the master branch, so drop me a comment if you’re interested and I'll see if I can clean it up.


check out ibdom, and some background/history here: Recommended JavaScript HTML template library for JQuery?


Could always go with jQuery-Templates: http://api.jquery.com/category/plugins/templates/


What about http://www.enfusion-framework.org

Stuff like this:

<span template>Our telephone number is {phone}.</span>

<span session>You are logged in as {nickname}.</span>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜