21

So I've seen this post on JavaScript Micro-Templating by John Resig and I have a need for a micro-templating engine like this.

But he saids in the post that he'll keep a more-refined version in his Secrets of the JavaScript ninja book and also mentions that he'd like to see it evolves.

So I'm wondering, is there a more stable/advanced version of this Micro-templating engine by John Resig? If so, how can I obtain it? That JavaScript book is not available in my country.

Leon Bambrick
  • 26,009
  • 9
  • 51
  • 75
chakrit
  • 61,017
  • 25
  • 133
  • 162

8 Answers8

5

You can definitely purchase the pdf online when it comes out as @James points out, regardless of your country of residence.

is there a more stable/advanced version of this Micro-templating engine by John Resig?

See Rick Stahl's blog (on a bunch of clientside template engines) where he fixes an issue with single quotes in Resig's Micro-Templating engine. That's about the only improvement to the source I've seen.

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • I'm using that now, it's great. Although it did make me write this craziness: $("input").each(function() { eval("data." + $(this).attr("id") + "=\"" + $(this).val() + "\";"); }); (That sets up a 'data' object with values of all input fields, which I then pass to the templating function, to make it very convenient to access field values.) – Steve Bennett Feb 24 '11 at 07:52
  • 1
    @Steve: `var data = {}; $("input").each(function() { data[this.id] = this.value });` See http://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object – Crescent Fresh Mar 02 '11 at 05:09
  • For a quick reference I created a repo out of his example: https://github.com/clouddueling/javascript-micro-templating – Michael J. Calkins Aug 25 '13 at 17:21
3

Also see jQote2. I'll quote from the site itself:

jQote (pronounced like Star Trek’s Chakotey) is basically a rewrite of John Resig’s awesome JavaScript Micro-Templating utility. I took his code and ported it to jQuery, overhauled the parsing / conversion part and extended it’s functionality to minimize everyone’s coding efforts.

Michael
  • 2,826
  • 4
  • 25
  • 18
2

Take a look at the jQuery plugin

https://github.com/vkiryukhin/vkTemplate ,

which is built on the John Resig's Micro-Templating engine. A "single quote" issue is fixed and engine is slightly simplified according plugin's architecture.

Demo and documentation at http://www.eslinstructor.net/vktemplate/

vadimk
  • 1,461
  • 15
  • 11
1

If you go to http://www.manning.com/resig/ you can pre-order the PDF that allows you to see the upcoming book.

James Black
  • 41,583
  • 10
  • 86
  • 166
1

simple templating engine... super small.. based on John Resigs code... with improvements. Only 335 Bytes and blazing fast and a lot of bugs from original code are fixed.

https://github.com/leolems/javascript/tree/master/templates

1

This is John Resig's (slightly modified) script, its from Rick Strahl's web (http://weblog.west-wind.com/posts/2008/Oct/13/Client-Templating-with-jQuery)

var _tmplCache = {}
this.tmpl= function(str, data) {
/// <summary>
/// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
/// and # # code blocks for template expansion.
/// NOTE: chokes on single quotes in the document in some situations
///       use &amp;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() + " # >";
}

It can be used like this: tmpl($('myHtmlTempl').html(), data);

I tested it and it works with "single quotes" (that was my main problem until i found this one). This version are ready to work with <# #> tags.

mzalazar
  • 6,206
  • 3
  • 34
  • 31
1

The template function in underscore.js is based on John Resig's micro templating engine. http://documentcloud.github.com/underscore/#template

benjamunky
  • 260
  • 2
  • 12
0

One minor improvement/customization that I've made is allow for hyphens in the id of the template. With the original code, this will not work:

<script type="text/html" id="my-awesome-template">
  <!-- template contents -->
</script>

It will actually just try to template the string "my-awesome-template", which will obviously just return "my-awesome-template".

To fix this, I modified the regex here in line 9 or so where it says

var fn = !/\W/.test(str) ?

to the following:

var fn = !/[^a-zA-Z0-9_-]/.test(str) ?
kimbo
  • 2,513
  • 1
  • 15
  • 24