How to use JQuery Micro templating Engine

Read the following the following link for background: Rick Strahl

Read my struggle stack with JQuery


<script src="somedir/jquery132-dev.js"/>
</script>
<script src="somedir/js/template-engine.js"/>
</script>

var _tmplCache = {}
this.parseTemplate = function(str, data) {
    /// <summary>
    /// Client side template parser that uses <#= #> and <# code #> expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            //                        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('');";

            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.htmlEncode() + " # >";
}

<html><head>
<script src="../../js/jquery132-dev.js"></script>
<script src="../../js/template-engine.js"></script>


<script>
//Data
var itemArray = [
               {name: "Social", value: "12345678"},
               {name: "cell1", value: "12345678"},
               {name: "cell2", value: "12345678"}
             ];
             
function onloadFunction()
{
   var s = $("#MyTemplate").html();
   var s1 = parseTemplate(s, {itemArrayData: itemArray});
   $("#target").html(s1);
}
</script>

<script id="MyTemplate" type="text/html">
 <# 
 for(var i=0; i < itemArrayData.length; i++)         
 {                  
      var item = itemArrayData[i];
 #>
     <p><#=item.name #>:<#=item.value #></p>
 <# } #>
</script>

</head>

<body onload="onloadFunction()">
<div id="target">
<p>target</p>
</div>
</body></html>

The engine is from John Resig. Rick has mortalized a bit which I have borrowed to put it in a separate file.

Take an array of name value pairs and write them as a series of paragraphs, one per each row in the array. When executed you will see the following output:


Social:12345678

cell1:12345678

cell2:12345678

is the microtemplating engine part of jquery?

Search for: is the microtemplating engine part of jquery?

A more recent post on these templates

Here is some history on where templates are heading in jquery

Roadmap for Jquery templates: 2011

jsrender home page

How to use jsrender?

Search for: How to use jsrender?

Hello jsrender introduction

where can i download jsrender.js?

Search for: where can i download jsrender.js?

jsrender reference

Search for: jsrender reference


<script src="http://borismoore.github.com/jsrender/jsrender.js"></script>

See if these docs from the author would help or not for some basics docs

jsrender reserved variables

Search for: jsrender reserved variables


<script id="movieTemplate" type="text/x-jsrender">
   <div>
      {{:#index+1}}: <b>{{>name}}</b> ({{>releaseYear}})
   </div>
</script>

documentation on converters

{{:value}} does not convert. Used to render values that include html markup

{{loc:value}} Uses custom converter.

{{html:value}} Converts using built-in HTML encoder. (Better security, but slight perf cost)

{{>value}} Alternative syntax for built-in HTML encoder.

if you expect the data to be not html in nature. This is useful when you have the html tags are in the template and the data is expected to be void of html tags.

Interesting that you can register functions to provide your own conversion much like what I do in aspire tags


<script id="movieTemplate" type="text/x-jsrender">
   <tr>
      <td>{{>title}}</td>
      <td>
         {{if languages}}
            Alternative languages: <em>{{>languages}}</em>.
         {{else subtitles}}
            Original language only... <br/>subtitles in <em>{{>subtitles}}</em>.
         {{else}}
            Original version only, without subtitles.
         {{/if}}
      </td>
   </tr>
</script>

<table>
   <thead><tr><th>title</th><th>languages</th></tr></thead>
   <tbody id="movieList"></tbody>
</table>

<script type="text/javascript">

   var movies = [
      {
         title: "Meet Joe Black",
         languages: "English and French",
         subtitles: "English"
      },
      {
         title: "Eyes Wide Shut",
         subtitles: "French and Spanish"
      },
      {
         title: "The Mighty"
      },
      {
         title: "City Hunter",
         languages: "Mandarin and Chinese"
      }
   ];

   $( "#movieList" ).html(
      $( "#movieTemplate" ).render( movies )
   );

</script>

$( "#movieList" ).html(
      $( "#movieTemplate" ).render( movies )
   );

the template "movieTemplate" is one "tr". So the jsrender automatically executes this once per element of the movies array.

if the "languages" element were to be an array by itself then, you could do this.


<script id="movieTemplate" type="text/x-jsrender">
   <tr>
      <td>{{>title}}</td>
      <td>
         {{for languages}}
            <div>
               <em>{{>name}}</em>
            </div>
         {{/for}}
      </td>
   </tr>
</script>

In short this is a valuable resource to understand these tags

Because jsrender does not have any javascript code in it, perhaps I Could use both jsrender and also the simple templating engine from John. Both may have strengths.

The simplicity of John's original version is it is javascript!!!

However once I am familiar with jsrender, I might choose to do render tags more.

This is much like what I do with aspireweb where I use a homegrown template for 90% of the code and switch to JSP when I need to do more limitless programmatic approach.