I’ve often wanted to extend Prototype’s Template class to allow setting default values for template fields if the user doesn’t pass them, so I wrote a simple wrapper class that does just that.
This allows you to create a 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 || {})); } });
Sample Usage:
var myTemplate = new TemplateWithDefaults('Hi There, #{name}!', {name: "Person"}); alert(myTemplate.evaluate()); alert(myTemplate.evaluate({name: "Paul"}));
Of course, you will need to include the prototype library for this to work.