Pinjasaur/templater.js

Support for defaults

mhamann opened this issue · 2 comments

If would be nice if a default value could be specified in the template string, such that it would be used if the object containing the replacement values was missing some, they were undefined, etc.

For example:

const data = {
  first_name: null,
  email: 'jrose@myco.com'
};

const template = templater('Welcome, {{ first_name | "visitor" }}!');

console.log(template(data));  // "Welcome, visitor!"

Hey Matt, thanks for taking the time to make a feature request. I'm not opposed to the idea of runtime defaults defined in the template, but I'd consider it a pretty significant effort to refactor the templating logic and add sufficient cases to the test suite.

If you (or anyone reading this) is interested in taking a stab at getting a PR out I'd happily accept that. It's just not something I'm able to personally undertake at the moment.

In the mean time, I can suggest a workaround: Object.assign(). Building off your example above, it would look something like

const defaults = {
  first_name: "visitor",
}

template(Object.assign({}, defaults, data))

with the caveat that falsy values e.g. null, undefined would have to be filtered out of the data object beforehand.

Thanks for the reply! Seems like a good workaround. I'd love to contribute if I get the time to do so—I definitely appreciate that you don't have the time either right now :-)

Thanks for this great little library! It works well for some browser-side templating work I needed to do!