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: 1727
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!
Nicola Gervasi
sintpro.com
SAN Partner
ngervasi
 
Posts: 1485
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
https://www.servoyforge.net
Velocity rules! If you don't use it, you don't know what you're missing!
User avatar
ptalbot
 
Posts: 1654
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!
Nicola Gervasi
sintpro.com
SAN Partner
ngervasi
 
Posts: 1485
Joined: Tue Dec 21, 2004 12:47 pm
Location: Arezzo, Italy

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

Postby sbutler » 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- Training Videos
Servoy Components- Plugins, Beans, and Web Components
Servoy Guy- Tips & Resources
ServoyForge- Open Source Components
User avatar
sbutler
Servoy Expert
 
Posts: 759
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
https://www.servoyforge.net
Velocity rules! If you don't use it, you don't know what you're missing!
User avatar
ptalbot
 
Posts: 1654
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: 1727
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 7 guests