mustache.js: Add option: Warning on unknown variables
Sometimes we make typos on variable names (even with autosuggest). It would be great if there was a configuration so mustache-js would generate a warning on ‘unknown’ variables, instead of giving back an empty string (eventhough it is spec-compliant).
The Mustache man-page says:
By default a variable "miss" returns an empty string. This can usually be configured in your Mustache library. The Ruby version of Mustache supports raising an exception in this situation, for instance.
About this issue
- Original URL
- State: open
- Created 8 years ago
- Reactions: 24
- Comments: 21
I’d prefer a hard error, so that, for instance, when using with Express it becomes a 500 response and not just a log somewhere while the end user is seeing an incorrectly rendered page (potentially very incorrectly rendered, depending on how the missing variable was supposed to be used); this could be even more useful in production than in local development, depending on how good your 500 page is vs. how bad the mis-rendered pages would be for your application’s functionality. Use of sections could still allow templates to ignore missing variables even with hard errors for direct use. And any higher-level use that needs to log the issue would be in control of the logging system, so we wouldn’t have to worry about, say, Mustache’s internal warning mechanism clobbering output from test runners or things like that.
I have a working prototype at https://github.com/ScottFreeCode/mustache.js, although I could use some help figuring out how to write a test for it.
My use-case is a bit different: I use Mustache to transform Terraform templates using Gulp. A missing variable can cause instances to not boot correctly, especially when substituting in free-form strings. I came up with a quick monkey-patch to get this functionality but it’s hardly ideal:
Notes:
However it worked well for my purposes and I’m sure someone can adapt it if required.
This is now fixed, and mustache-validator is working very well for me. Thank you @eliasm307!
For anyone that doesnt want to/cant move to handlebars I’ve made a small package to add validation to mustache
IMO interpreting
nullvalues as non-existing values is wrong.that object has a
nameproperty with a falsy value, and should therefore never be seen as invalid and therefore not a reason to throw.A more appropriate check would be to check if a requested property has been defined like we do in mustache.hasProperty().