Skip to content

Instantly share code, notes, and snippets.

@premasagar
Created August 12, 2010 17:52
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save premasagar/521352 to your computer and use it in GitHub Desktop.
Save premasagar/521352 to your computer and use it in GitHub Desktop.
A tiny, secure JavaScript micro-templating script. It doesn't use eval or (new Function), so it cannot execute malicious code.
/*
== Tim ==
A tiny, secure JavaScript micro-templating script.
This has now moved to:
github.com/premasagar/tim
*/
@aron
Copy link

aron commented Sep 7, 2010

Hey Prem,

What a useful little function. I don't think you need to slice the tag on line 53 as the captured tokens are passed as arguments into the callback function. eg.

return template.replace(pattern, function (tag, ref) {
  var path = ref.split("."),
      len = path[length],
      ...

Unless you're doing it for another reason?

@premasagar
Copy link
Author

Aha! Thanks, Aron. You are right. Updated the Gist...

@bruntonspall
Copy link

Awesome prem, I'm so going to use that in projects from now on.

@premasagar
Copy link
Author

Great. Please do, Michael. Let me know if you put it to good use.

@premasagar
Copy link
Author

I just added a little debugging block, to help track down missing properties in the data object, and an option third argument "notFound", which can be used as the default string when a property is not found in the data object. See the notes at the top of the script.

(BTW - I'm probably going to spin this off into its own GitHub project repository soon).

@premasagar
Copy link
Author

I've now moved Tim to http://github.com/premasagar/tim

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