Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for defaults #1

Open
mhamann opened this issue Mar 12, 2022 · 2 comments
Open

Support for defaults #1

mhamann opened this issue Mar 12, 2022 · 2 comments

Comments

@mhamann
Copy link

mhamann commented Mar 12, 2022

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!"
@Pinjasaur
Copy link
Owner

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.

@mhamann
Copy link
Author

mhamann commented Mar 24, 2022

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!

@Pinjasaur Pinjasaur mentioned this issue Jul 29, 2022
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants