Created
December 27, 2013 01:42
-
-
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();
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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