Tim: A tiny, secure JavaScript micro-templating script.

Find out how to get things done with Servoy. Post how YOU get things done with Servoy

Tim: A tiny, secure JavaScript micro-templating script.

Postby david » Sat Dec 22, 2012 12:51 am

Modified slightly for Servoy. Source: https://github.com/premasagar/tim

"Don't you just hate having to write HTML with a mess of string concatenation that clutters up your JavaScript?:"

Code: Select all
var myHTML = "<ul class='" + myClass + "'>" +
    "<li id='" + theId + "'>" + liContents + "</li>" +
    // etc, etc, etc


Tim lets you write simple templates that uses JavaScript's familiar dot notation. You pass in a JavaScript object that contains all the relevant strings, and they are then substituted into the template:"

Code: Select all
tim("Hello {{place}}", {place: "world"});
// "Hello world"


Servoy version. Rename the method (optional) and paste it somewhere in your solution:

Code: Select all
/**
* Tim (lite): A tiny, secure JavaScript micro-templating script.
*   github.com/premasagar/tim
*   
* @param {String} template
* @param {Object} data
*
* @example
*       CMS.markup.merge("Hello {{place}}", {place: "world"})
*          > Hello world
*       CMS.markup.merge("Hello {{place}}. My name is {{person.name}}.", { place: "Brighton", person: { name: "Prem" } })
*         > Hello Brighton. My name is Prem.
*
* @properties={typeid:24,uuid:"E93C4B64-5AC4-4A50-A6EF-8506C5D07371"}
*/
function merge(template, data){

    var start   = "{{",
        end     = "}}",
        path    = "[a-z0-9_][\\.a-z0-9_]*", // e.g. config.person.name
        pattern = new RegExp(start + "\\s*("+ path +")\\s*" + end, "gi"),
        undef;

        // Merge data into the template string
        return template.replace(pattern, function(tag, token){
            path =    token.split(".")
            var     len = path.length,
                   lookup = data,
                   i = 0;

            for (; i < len; i++){
                lookup = lookup[path[i]];
               
                // Property not found
                if (lookup === undef){
                    throw "tim: '" + path[i] + "' not found in " + tag;
                }
               
                // Return the required value
                if (i === len - 1){
                    return lookup;
                }
            }
        });
}
David Workman, Kabootit

Image
Everything you need to build great apps with Servoy
User avatar
david
 
Posts: 1723
Joined: Thu Apr 24, 2003 4:18 pm
Location: Washington, D.C.

Re: Tim: A tiny, secure JavaScript micro-templating script.

Postby ngervasi » Mon Dec 24, 2012 1:28 am

Cool!! This will save me hours and hours, tnx David!
ngervasi
 
Posts: 1475
Joined: Tue Dec 21, 2004 12:47 pm
Location: Arezzo, Italy

Re: Tim: A tiny, secure JavaScript micro-templating script.

Postby ptalbot » Mon Dec 24, 2012 3:15 am

ngervasi wrote:Cool!! This will save me hours and hours, tnx David!

For real? Have you looked at Velocity for this kind of merging? This has been around for a couple of years:
Code: Select all
var merged = plugins.VelocityReport.evaluateWithContext(whateverComplexTemplateYouWantAsAString, whateverComplexObjectYouWant);
Patrick Talbot
Freelance - Open Source - Servoy Valued Professional
http://www.servoy-stuff.net
https://www.servoyforge.net
--------------------------------------------
Servoy 5.2.16 / 6.0.9 / 6.1.6 / 7.3.1
All OSes / Java 5 & 6 & 7
User avatar
ptalbot
 
Posts: 1612
Joined: Wed Mar 11, 2009 5:13 am
Location: Montreal, QC

Re: Tim: A tiny, secure JavaScript micro-templating script.

Postby ngervasi » Mon Dec 24, 2012 2:13 pm

Ouch! How could I have missed this one!?!? Probably because the sample code doesn't show an actual call to it.
Tnx Patrick!
ngervasi
 
Posts: 1475
Joined: Tue Dec 21, 2004 12:47 pm
Location: Arezzo, Italy

Re: Tim: A tiny, secure JavaScript micro-templating script.

Postby goldcougar » Mon Dec 24, 2012 7:24 pm

I've been using this:

Code: Select all
/**
*  Similar to utils.stringReplaceTags, but supports only form variables, or Record Object,  generic objects with named properties
*
* @properties={typeid:24,uuid:"BFECB7EA-B144-4C5C-BDCD-85439C51DEBA"}
*/
function string_tag_replace(text, form) {
   if(!text || !form)
      return

   //use regex with function handler to convert %%formVar%% to form[formVar] so we render value
   var result =  text.replace(/%%[\w-]+%%/g, function(match){
      var formVar = match.replace(/%/g, "")
      return form[formVar]
   })
   
   //make recursive
   if(result.indexOf("%%") != -1) //if there are still tags in the result, run it again
      return string_tag_replace(result, form)
   else   
      return result
}


Then you can do things like this:
Code: Select all
//works with form vars, dataproviders, relations, etc.
var result = globals.string_tag_replace(stringWithTags, this)
Scott Butler
iTech Professionals, Inc.
SAN Partner

Servoy Consulting & Development
Servoy University- Free Training Videos
Servoy Guy- Free Plugins, Tips & Resources
ServoyForge- Open Source Servoy Components
User avatar
goldcougar
Servoy Expert
 
Posts: 657
Joined: Sun Jan 08, 2006 7:15 am
Location: Cincinnati, OH

Re: Tim: A tiny, secure JavaScript micro-templating script.

Postby ptalbot » Mon Dec 24, 2012 7:44 pm

Unless you don't actually use Velocity (in which case you really are missing something in your Servoy stack) and this is a contest on who's got the best regular expression, I don't see the point of crafting these kinds of functions that will always be much less powerful than the Velocity templating language (that was made and optimized for this very purpose and is in production use in thousands of applications) and the wrappers included in the Velocity plugin (that were made to make Velocity Servoy aware and leverage that power)...
Patrick Talbot
Freelance - Open Source - Servoy Valued Professional
http://www.servoy-stuff.net
https://www.servoyforge.net
--------------------------------------------
Servoy 5.2.16 / 6.0.9 / 6.1.6 / 7.3.1
All OSes / Java 5 & 6 & 7
User avatar
ptalbot
 
Posts: 1612
Joined: Wed Mar 11, 2009 5:13 am
Location: Montreal, QC

Re: Tim: A tiny, secure JavaScript micro-templating script.

Postby david » Tue Dec 25, 2012 3:45 am

ptalbot wrote:Unless you don't actually use Velocity (in which case you really are missing something in your Servoy stack) and this is a contest on who's got the best regular expression, I don't see the point of crafting these kinds of functions that will always be much less powerful than the Velocity templating language (that was made and optimized for this very purpose and is in production use in thousands of applications) and the wrappers included in the Velocity plugin (that were made to make Velocity Servoy aware and leverage that power)...


I learned something from Scott's post (the Servoy-specific angle is cool) and we use Velocity (thought everyone knew about Velocity's capabilities). Different variations may have their uses...even if for learning purposes.

But we actually use this over velocity in some instances just for its brevity. Like for..."micro-templating" tasks....
David Workman, Kabootit

Image
Everything you need to build great apps with Servoy
User avatar
david
 
Posts: 1723
Joined: Thu Apr 24, 2003 4:18 pm
Location: Washington, D.C.


Return to How To

Who is online

Users browsing this forum: No registered users and 1 guest