Search code examples
javascripthtmlcssawesomium

How can I create a list on a webpage, where each item is based on a template, using Javascript?


I am creating a page, intended to be used as a GUI control with Awesomium. In this page I want a list, the content of which is controlled by the application at runtime.

Awesomium allows web pages to be rendered to a buffer and, for example, be drawn as the texture of an object in a 3D app, therefore there is no 'server' to run server side code, and communication between the 'GUI' and the application is done almost entirely through Javascript function calls and callbacks.

The list will be made up of a number of <div>s, each one relatively complex, and so I would like to create a template for an entry which can be populated and added to the list.

So far I have been doing something similar to:

    function refresh() {
        contentpane.innerHTML = '';
        var i = 0;
        for (i = 0; i < page.contentlist.length; i++) {
            contentpane.innerHTML += '<div id=\'' + page.contentlist[i] + '\'class="button" onclick=page.callback("clicked",id) > <img src="\screenshot.jpg"/> <label ></label> </div>';
        }
    }

But the more complex my list entries become the more unwieldy this is, so I am thinking there must be a better way.

What is the simplest method, to create a list of templated items within a Javascript function?

Is there anything similar to say, WPF's DataTemplate system that I could use?


Solution

  • Underscore.js has a template engine you could take a look at. You can also put the templates into separate files and load them via ajax when necessary.

    Say you have following template:

    <script type="text/template" id="tmpl-listentry">
      <div id='<%= content %>' class="button" onclick='page.callback("clicked",id)'>
        <img src="/screenshot.jpg" />
        <label></label>
      </div>
    </script>
    

    You can then use it like this after loading it and attaching it to your doc:

    function refresh() {
        var i = 0,
            tmplElem = document.getElementById('tmpl-listentry'),
            compiled = _.template(tmplElem.innerHTML);
    
        contentpane.innerHTML = '';
        for (i = 0; i < page.contentlist.length; i++) {
            contentpane.innerHTML += compiled({content: page.contentlist[i]});
        }
    }
    

    Note: Of course you should rather cache your compiled template instead of compiling it on every refresh.