0

I understand that we can use:

var ele = "<div></div>";
$('body').append(ele);

However this is not as flexible as plain HTML, as all HTML is quoted...

I saw jQuery-templ so that we can use:

<script id='tmpl' type='text/html'>
    <div>test</div>
</script>
<script>
    $.tmpl('#tmpl').appendTo('body');
</script>

This is good, but this project is not continuing any more (though this is so useful!)

Is there anything similar to that?

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
  • I have a question why this type of code is not flexible as plain html? `var ele = "
    "; $('body').append(ele);`
    – The Mechanic Feb 15 '13 at 04:46
  • @Sarfaraz Because the template div can be really long, and the quotes has to continue for many lines. Sometimes you have "
    " so you need to escape the inner level of quotes..
    – SwiftMango Feb 15 '13 at 04:49
  • you dont want to use type="text/html" you should use type="text/template" and then use $('#tmpl').html() – Subtubes Feb 15 '13 at 05:04
  • ` ` I've tried this but this is not working can you please explain – The Mechanic Feb 15 '13 at 09:22
  • @Sarfaraz it should be '#tmpl'. I missed a sharp – SwiftMango Feb 15 '13 at 14:03

3 Answers3

2

you want some thing template engine. then here are the list.

  1. KnockOutJS KnockOut JS
  2. HandlerBar HandleBar JS
  3. Mustache Mustache

or alternativiely you can choose your own template engine based on your requirement. Template Chooser or even from this link Template chooser

Community
  • 1
  • 1
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
2

The very light weight underscore library has a template function. This also allows you to use erb style <% %> to inline javascript code.

Also John Resig (jQuery creator) wrote a micro templating function you can drop into your code without calling a library.

Jacob Dalton
  • 1,643
  • 14
  • 23
1

You can also do this without using any library (pure JS) (demo)

var list = [
        'item1',
        'item2',
        'item3'
    ],
    tmpl = '<li>{item}</li>',
    i, t = '';

for (i = 0; i < list.length; i++) {
    t += tmpl.replace(/\{item\}/g, list[i]);
}
document.getElementById('list').innerHTML = '<ul>' + t + '</ul>';
Mottie
  • 84,355
  • 30
  • 126
  • 241