1

Possible Duplicate:
JavaScript: How should I generate a lot of HTML?

I feel really stupid doing something like this:

var html = '<div><ul>';
for(var i=0; i<10; i++) {
   html += '<li>' + i + '</li>';
}
html += '</ul></div>';
$("body").html(html);

Isn't there a way to use templates instead of concatenating strings like that? I know there's the option of populating existing elements with JS and changing the display to block when they need to appear, but it seems rather hackish and annoying, especially when using loops.

I'm open to any front-end template/framework suggestions as well.

This question has probably been asked before, but I couldn't find any clues on SO. Any insight would be greatly appreciated.

EDIT:

To clarify, I'd be interested in something like this:

// li_list.haml
%div
   %ul
      - for i in #{range}
         %li i

// app.js
// require li_list.haml with {range: 10}
Community
  • 1
  • 1
Gal
  • 23,122
  • 32
  • 97
  • 118

3 Answers3

3

You can definitely use templates, but that will require an external library.

Personally I like KnockoutJs, which has templating, two-way binding to the dom, and other goodies. Here's their demo on templating

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
2

I know it wasn't tagged, but seeing as your question looks to be using it: jQuery has a tmpl plugin listed in their API documentation.

For a non-jquery solution, Jon Resig has a great article about his micro-templating technique.

Finally, if you're simply concatenating a bunch of stuff, arrays work wonders:

Instead of:

var html = '<div><ul>';
for(var i=0; i<10; i++) {
   html += '<li>' + i + '</li>';
}
html += '</ul></div>';
$("body").html(html);

You could use:

var html,
    i;
html = ['<div><ul>'];
for (i = 0; i < 10; i += 1) {
    html.push('<li>', i, '<li>')
}
html.push('</ul></div>');
$('body').html(html.join(''));

Not a significant difference, but at least you can perform array manipulation.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

Try Prototype Template.

You might also want to try Closure JS templates.

demonkoryu
  • 1,247
  • 10
  • 27