0

I am looking for javascript library which can do something like

var items = [1, 2];
var html = div(
    ul({
      id: "some-id",
      class: "some-class"
    })(items.each(function(item) {
      return li(item);
    }));
html == "<div><ul id='some-id' class='some-class'><li >1</li><li>2</li></ul></div>"
3
  • 2
    What the hell are you talking about? :) Commented May 25, 2010 at 10:36
  • I presume he wants some kind of templating engine written in JavaScript with syntax similar to the first segment to produce HTML similar to the second segment. Commented May 25, 2010 at 10:37
  • Do you want a templating engine? It's hard to answer when we are not clear what you are asking for. Commented May 25, 2010 at 11:35

4 Answers 4

1

Have a look at Douglas Crockford's supplant() method:

param = {domain: 'valvion.com', media: 'http://media.valvion.com/'};
url = "{media}logo.gif".supplant(param);
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to use jQuery:

var $ul = $('<ul />',{
    "class":" some-class",
    "id": "some-id"
});
$.each(items,function(index,value) {
    $('<li />').text(value).appendTo($ul);
});
$ul.appendTo($('body'))

Although in this case, you can do it in pure javascript too:

var ul = document.createElement('ul');
    ul.setAttribute('id',   'some-id');
    ul.setAttribute('class','some-class');
for(var i in items)
{
    var li = document.createElement('li');
        li.innerText = items[i];
    ul.appendChild(li);
}
document.body.appendChild(ul)

Comments

0

John Resig has a great template system. The example he uses to illustrate its capability is exactly what you want to do.

You can use a script with the following syntax to create the output you want:

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

And feed it data with the following call in javascript:

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);

Comments

0

So, I write it by myself. http://jshtmlbuilder.codeplex.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.