Skip to content

Instantly share code, notes, and snippets.

@paulferrett
Created December 27, 2013 01:42
Show Gist options
  • Save paulferrett/8141283 to your computer and use it in GitHub Desktop.
Save paulferrett/8141283 to your computer and use it in GitHub Desktop.
This allows you to create a prototype javascript template, but gives you one extra parameter where you can define default values for anything not passed by the user to .evaluate();
/**
* Create a new wrapper to the Prototype Template class to
* allow default values for the template
*
* @param template
* @param defaults
*/
var TemplateWithDefaults = Class.create(Template, {
initialize: function($super, template, defaults, pattern) {
this.defaults = defaults || {};
$super(template, pattern);
},
evaluate: function($super, object) {
// Clone the defaults for this instance to preserve our actual
// defaults across evaluations of this template
var defaults = Object.clone(this.defaults);
return $super(Object.extend(defaults, object || {}));
}
});
// Example Usage:
var myTemplate = new TemplateWithDefaults('Hi There, #{name}!', {name: "Person"});
console.log(myTemplate.evaluate());
console.log(myTemplate.evaluate({name: "Paul"}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment