views:

277

answers:

10

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

A: 

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

Daniel A. White
I specifically don't want to use a script block, because I want to be able to use this across several pages and have one place where I modify my templates.
VarLogRant
+1  A: 

There are several good ones out there:

Mustache.js
Pure.js
Json Template

If you want a jQuery version, Tempest looks good.

Sean Vieira
+1  A: 

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

Juan Mendes
A: 

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.

Jay
A: 

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.

Sidnicious
the most-recently git-cloned stencil.js won't work with the most-recently git-cloned jquery-haml.js. Did some poking to see what the problem is. That being said, once I got the library issue worked out, it worked perfectly. I like it.
VarLogRant
A: 

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.

Mic
A: 

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.

skrat
+1  A: 

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
cofiem
It works with but doesn't require jQuery. It allows you to have a separate file for your markup. I like it.
VarLogRant
A: 

Thank you for all the responses. I am trying many of them on for size, seeing which fit.

I have certain biases I have (pro-Perl, pro-HTML, anti-Java) that would cause me to prefer some tools and avoid others. Google Closure, for example, is something that would ill-fit my workflow, while it may be the bee's knees for someone else.

So, I'm answering my question to get it out of the unanswered queue, then starting to work up test cases for a lot of these libraries. Thanks again, all of you.

VarLogRant