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

Include name of replacement in filter function #274

Open
cpetrov opened this issue Feb 9, 2024 · 1 comment
Open

Include name of replacement in filter function #274

cpetrov opened this issue Feb 9, 2024 · 1 comment

Comments

@cpetrov
Copy link

cpetrov commented Feb 9, 2024

Is your feature request related to a problem? Please describe.
Currently, when a replacement is not defined, Eta will render undefined in its place:

const eta = new Eta()
const res = eta.renderString("Hello <%= it.name %>", {}) // Hello undefined

This is not ideal, as it will lead to undefined being rendered in the output. This is rarely desired.

As recommended in the related issue #28, one can use filterFunction to handle missing replacements:

const eta = new Eta({
  autoFilter: true,
  filterFunction: (val) => {
    if (val == null) throw new Error('Replacement missing');
    return String(val);
  }
})
const res = eta.renderString("Hello <%= it.name %>", {}) // Error: Replacement missing

... however, the filter function does not have access to the name of the replacement that is missing, so it is not possible to provide a helpful error message.

Describe the solution you'd like
The filter function could be called with the name of the missing replacement as a second argument to enable helpful error messages:

const eta = new Eta({
  autoFilter: true,
  filterFunction: (val, name) => {
    if (val == null) throw new Error(`Replacement "${name}" missing`);
    return String(val);
  }
})
const res = eta.renderString("Hello <%= it.name %>", {}) // Error: Replacement "name" missing
@nebrelbug
Copy link
Collaborator

@cpetrov I like this idea, but it's difficult to implement without writing something to try and parse JS. For example, what should happen if somebody writes <%= it.name + "!" %>? What should happen if somebody writes <%= undefined %>? Those are both possibilities with Eta.

I am open to a PR though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants