How to use JQuery Micro templating Engine

satya - Friday, August 07, 2009 3:41:14 PM

Read the following the following link for background: Rick Strahl

Read the following the following link for background: Rick Strahl

satya - Friday, August 07, 2009 3:42:08 PM

Read my struggle stack with JQuery

Read my struggle stack with JQuery

satya - Friday, August 07, 2009 3:43:12 PM

You will need to include these two .js files


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

satya - Friday, August 07, 2009 3:45:01 PM

Here is the source code for template-engine.js borrowed from Rick Strahl


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() + " # >";
}

satya - Friday, August 07, 2009 3:46:46 PM

Here is the complete html file that you can test in your browser


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

satya - Friday, August 07, 2009 3:48:02 PM

Credits on the micro templating engine

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

satya - Friday, August 07, 2009 3:50:05 PM

What does the code above do?

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

satya - Fri Oct 05 2012 13:31:56 GMT-0400 (Eastern Daylight Time)

is the microtemplating engine part of jquery?

is the microtemplating engine part of jquery?

Search for: is the microtemplating engine part of jquery?

satya - Fri Oct 05 2012 13:34:38 GMT-0400 (Eastern Daylight Time)

A more recent post on these templates

A more recent post on these templates

satya - Fri Oct 05 2012 13:36:37 GMT-0400 (Eastern Daylight Time)

Here is some history on where templates are heading in jquery

Here is some history on where templates are heading in jquery

satya - Fri Oct 05 2012 13:45:21 GMT-0400 (Eastern Daylight Time)

Roadmap for Jquery templates: 2011

Roadmap for Jquery templates: 2011

satya - Fri Oct 05 2012 13:48:02 GMT-0400 (Eastern Daylight Time)

jsrender home page

jsrender home page

satya - Fri Oct 05 2012 14:06:10 GMT-0400 (Eastern Daylight Time)

How to use jsrender?

How to use jsrender?

Search for: How to use jsrender?

satya - Fri Oct 05 2012 14:29:30 GMT-0400 (Eastern Daylight Time)

Hello jsrender introduction

Hello jsrender introduction

satya - Fri Oct 05 2012 14:34:19 GMT-0400 (Eastern Daylight Time)

where can i download jsrender.js?

where can i download jsrender.js?

Search for: where can i download jsrender.js?

satya - Fri Oct 05 2012 14:36:06 GMT-0400 (Eastern Daylight Time)

jsrender reference

jsrender reference

Search for: jsrender reference

satya - Fri Oct 05 2012 14:37:17 GMT-0400 (Eastern Daylight Time)

Here is what you need to include


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

satya - Fri Oct 05 2012 14:38:37 GMT-0400 (Eastern Daylight Time)

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

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

satya - Fri Oct 05 2012 14:42:25 GMT-0400 (Eastern Daylight Time)

jsrender reserved variables

jsrender reserved variables

Search for: jsrender reserved variables

satya - Fri Oct 05 2012 14:42:37 GMT-0400 (Eastern Daylight Time)

an example


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

satya - Fri Oct 05 2012 14:44:17 GMT-0400 (Eastern Daylight Time)

documentation on converters

documentation on converters

satya - Fri Oct 05 2012 14:45:05 GMT-0400 (Eastern Daylight Time)

Repeated here for a quick look

{{: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.

satya - Fri Oct 05 2012 14:49:42 GMT-0400 (Eastern Daylight Time)

use the greater than sign

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.

satya - Fri Oct 05 2012 14:50:22 GMT-0400 (Eastern Daylight Time)

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

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

satya - Fri Oct 05 2012 14:51:47 GMT-0400 (Eastern Daylight Time)

Using if/else


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

satya - Fri Oct 05 2012 14:54:05 GMT-0400 (Eastern Daylight Time)

Apparently this gets called once for each element in the array


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

satya - Fri Oct 05 2012 14:55:50 GMT-0400 (Eastern Daylight Time)

movies is an array: Special built-in array behavior


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

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

satya - Fri Oct 05 2012 14:58:01 GMT-0400 (Eastern Daylight Time)

Nested behavior

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>

satya - Fri Oct 05 2012 14:58:53 GMT-0400 (Eastern Daylight Time)

In short this is a valuable resource to understand these tags

In short this is a valuable resource to understand these tags

satya - Fri Oct 05 2012 15:01:43 GMT-0400 (Eastern Daylight Time)

So....My thought

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.

It will be interesting to see how Drupal's render arrays and its templating compares!!

A much detailed treatment on jsrender at msdn


var template = $.templates("some-template-name", templateAsAString);
var expandedHTML = $.render.some-template-name(json-data-object);

Here is the demo link:02_compiling-named-templates-from-strings

Once you get there you need to see view source to see the code. I might reprint it here for a quick ref


<script type="text/javascript">
   var movies = [
      { name: "The Red Violin", releaseYear: "1998", director: "Fran�ois Girard" },
      { name: "Eyes Wide Shut", releaseYear: "1999", director: "Stanley Kubrick" },
      { name: "The Inheritance", releaseYear: "1976", director: "Mauro Bolognini" }
   ];

   /* Compile markup as named templates */
   $.templates({
      titleTemplate: "<tr><td colspan=3>{{>name}}</td></tr>",
      detailTemplate: "<tr><td>{{>name}}</td><td>Released: {{>releaseYear}}</td><td>director: {{>director}}</td></tr>"
   });

   var details = true;

   function switchTemplates() {
      var html;

      details = !details;

      /* Render using the other named template */
      if ( details ) {
         $( this ).text( "Show titles only" );
         html = $.render.detailTemplate( movies );
      } else {
         $( this ).text( "Show full details" );
         html = $.render.titleTemplate( movies );
      }
      $( "#movieList" ).html( html );
   }

   $( "#switchBtn" ).click( switchTemplates );

   switchTemplates();
</script>

#data is a keyword that represents the object being iterated say in a for loop

You can use #parent to go up the tree


somemodel={
   a:b,
   c:d
   loop: { ...}
}

{{for loop}}
    {{:#parent.parent.data.a}}
{{/for}

See the link here from the author

is there a shortcut for #parent.parent.data in jsrender?

Search for: is there a shortcut for #parent.parent.data in jsrender?

Very nice chooser for a list of templating engines


dom.js
dot.js
dust.js
ejs
handlebars.js
hogan.js
icanhaz.js
jade
jsrender
markup
microtemplating
mustache
Nunjucks
Plates
pure
Transparency
Underscore

A basic guide to jsrender

Search for: A basic guide to jsrender

Try this link which seem to list basic needs