开发者

Is there a better way populate HTML widgets than building strings and setting innerHTML?

With XML XSLT, it is possible to build a nice template in HTML, convert it to XSLT and use xml data coming from the server to dynamically populate widgets on the client side.

JSON and JSONP are great for interacting 开发者_C百科with the server side and manipulating the data in JS. When it comes to rendering the JSON data, most examples I've seen use JS to concatenate an ugly string and set the innerHTML of some element to render it.

Is there an easy browser compatible way of creating html widgets and populating them with JSON that doesn't involve string banging or building loads of DOM elements?


As mentioned in other answers, what you're looking for is a javascript based templating language. There is a pretty good list going in this related question. Just to highlight a couple, mustache is clean, simple and ported to many many languages. I believe its being used by Twitter. Google Closure has template language that works in both JavaScript and Java. That's been battle tested by Google obviously.

Other major JS libraries each have templating as plugins or part of the library. I know jQuery has at least one plugin and is planning one on the roadmap for v1.5. Dojo has a clone of Django's templating language that looks pretty nice.

There are others, but I think that's going to be the cream of the crop.

I don't actually use any of these, because I use a home grown one, but I can tell you that they are very nice to work with and I highly recommend them over string concatenation or doing more work on the server.


You should see this blog post by John Resiq: JavaScript Micro-Templating

It has a simple micro-templating code you can re-use. It goes like this:

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

So you template would be in the markup:

<script type="text/html" id="item_tmpl">
  <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
    <div class="grid_1 alpha right">
      <img class="righted" src="<%=profile_image_url%>"/>
    </div>
    <div class="grid_6 omega contents">
      <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
    </div>
  </div>
</script>

To use it:

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

To be clear - the above example was taken from the blog post and is not my code. Follow the link for more info.


You could use jQuery and some sort of jQuery Plugin for Templates. For example http://ivorycity.com/blog/jquery-template-plugin/ (have a look at this page, there are some nice samples)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜