Search code examples
jquerytemplatesjquery-pluginsjquery-widgets

jQuery custom widgets: how can I include a html template?


I must be missing something basic here but while developing a custom jQuery widget, how do we include a html template as part of the widget like we do with dojo custom widgets? Currently, my jQuery custom widget is generating the needed html in JavaScript and I am trying to take that out into a html template and include it with the custom widget. Thoughts?


Solution

  • You can have a look at Handlebars.js. THis is a jQuery template plugin and The syntax is pretty easy

    Declare a Templae with script tag

      <script id="entry-template" type="text/x-handlebars-template">
        <div class="entry">
            <h1>{{title}}</h1>
            <div class="body">
               {{body}}
            </div>
        </div>
      </script>
    

    Then fetch and compile that template like this

      var source   = $("#entry-template").html();
      var template = Handlebars.compile(source);
    

    Then you can render that template by passing data for palceholders like this

     var context = {title: "My New Post", body: "This is my first post!"}
     var html    = template(context); 
    

    After this you will have the ful html in html variable which you can use in any jQuery DOM manipulation method like $.append.

    Working Fiddle