Null attribute should work in the same way as empty string attribute
acmattos opened this issue · 2 comments
Mustache is behaving in an unexpected way from my point of view. Some samples will describe the scenario in an understandable way. Please, go to http://mustache.github.io/#demo
Hit the "Render template" button. You are supposed to see this HTML:
Colors
But now, replace JSON for this code below:
{
"header": "Colors", "name": "REPLACED BY ME!",
"items": [
{"name": null, "first": true, "url": "#Red"},
{"name": "green", "link": true, "url": "#Green"},
{"name": "blue", "link": true, "url": "#Blue"}
],
"empty": false
}
You are supposed to see this HTML:
Colors
Now, replace JSON for this code below:
{
"header": "Colors", "name": "REPLACED BY ME!",
"items": [
{"name": "", "first": true, "url": "#Red"},
{"name": "green", "link": true, "url": "#Green"},
{"name": "blue", "link": true, "url": "#Blue"}
],
"empty": false
}
You are supposed to see this HTML:
Colors
I don't know if there is a way to get null working in the same way as empty string for the presented scenario. But it looks like an undesired behavior the way the mustache is working right now.
Hi there @acmattos, sorry for the late reply!
From a distance I'd agree with the issue title, as both null
and ""
are both falsy they should in most scenarios behave the same. Our falsy
test files seen in ./test/_files/falsy.mustache | .js | .txt
amongst other falsy tests asserts that behaviour.
What you're describing here is a bit more complex than the ordinary falsy treatment in my eyes. What we're getting into here is when mustache decides to "fall through" and use a different value (from higher up in the view context if you will).
The fall through behaviour is really handy. I understand it feels a bit weird, knowing in JavaScript we have undefined
which might have felt more intuitively to use for this behaviour instead of null
. I think we've ended up with what we have today because of mustache being a standard that's implemented in multiple languages. Most languages have null
, not so many have both null
and undefined
like we do in JavaScript.
For example in Java. For that fall back to happen, we'd have no other choice but to use null
. And to make sure we could have used the same templates + views being rendered in Java and JavaScript, we have to choose what's common between the two (and of course there's more than two languages to consider).
Bottom line: what we have today is deliberate. It might not feel intuitive when seen from JavaScript's point of view, but I'm hoping my ramblings above gives you more context as to why we've ended up here?
Closing this for now as it seem to be the expected behaviour.