SwiftMango
SwiftMango

Reputation: 15284

How to construct HTML template and add to DOM?

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?

Upvotes: 0

Views: 2327

Answers (3)

Jacob Dalton
Jacob Dalton

Reputation: 1693

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.

Upvotes: 2

Mottie
Mottie

Reputation: 86413

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>';

Upvotes: 1

Ravi Gadag
Ravi Gadag

Reputation: 15861

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

Upvotes: 2

Related Questions