Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created June 11, 2011 04:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cowboy/1020250 to your computer and use it in GitHub Desktop.
Save cowboy/1020250 to your computer and use it in GitHub Desktop.
Ghetto fabulous templating system. More ghetto than fabulous.
// Ghetto fabulous template system for replacing values in strings. If {{.foo}}
// or {{.bar[0].baz}} is encountered (leading . or ( or [ char), attempt to
// access properties of data object like `data.foo` or `data.bar[0].baz`.
// Alternately, if {{foo}} or {{bar("baz")}} is encountered (no leading dot),
// simply evaluate `foo` or `bar("baz")`. If an error occurs, return empty
// string. Oh yeah, you have to pass the result of ghettoTmpl to eval. :)
var ghettoTmpl = function(data, str) {
if ( typeof data === "string" ) {
str = data;
data = {};
}
GHETTO_TMPL_DATA = data;
GHETTO_TMPL_STR = str;
return "["
+ "GHETTO_TMPL_STR.replace(/\\{\\{(([.[(])?.*?)\\}\\}/g, function(_, str, dot) {"
+ "return eval('try{' + (dot ? 'GHETTO_TMPL_DATA' : '') + str + '}catch(e){\"\"}');"
+ "})"
+ ",GHETTO_TMPL_DATA = GHETTO_TMPL_STR = null][0]";
}
var scope = "global";
// scope: global
console.log(eval(ghettoTmpl("scope: {{scope}} {{wont-error}} {{.wont-error}}")));
function test() {
var scope = "local";
var obj = {
prop: 123,
getter: function() { return this.prop; }
};
// scope: local prop: 123 123
console.log(eval(ghettoTmpl("scope: {{scope}} prop: {{obj.prop}} {{obj.getter()}}")));
// scope: local prop: 123 123
console.log(eval(ghettoTmpl(obj, "scope: {{scope}} prop: {{.prop}} {{.getter()}}")));
}
test();
@malsup
Copy link

malsup commented Jun 14, 2011

I'd reorder the args and have str come first. data is optional.

@cowboy
Copy link
Author

cowboy commented Jun 23, 2011

Ok, Mike, data is now optional... but it's still first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment