framework
framework copied to clipboard
Allow to omit an attribute passed to a component
- Maizzle Version: 1.4.0
- Node.js Version: 16.13.1
Hey there! I've got a feature request following my recent stream. I was stuck at doing this and think the way it works today in Maizzle is counter-intuitive.
Say I've got a component card.html
that can have a category
passed to it. The card would then display the category if it's present, but omit it otherwise.
<!-- src/components/card.html -->
<if condition="category">
{{ category}}
</if>
<content></content>
We should be able to call this component from within a template without triggering any error:
<!-- templates/foo.html -->
<component src="src/components/card.html" category="Kittens">…</component>
<component src="src/components/card.html">…</component>
Currently, the second occurrence (without the category
attribute) triggers an error. The solution is to add an empty category=""
attribute. This works but I feel is counter-intuitive to the way the <if condition>
tag works in layouts with front matter variables.
Unfortunately the way variables are currently parsed in posthtml-modules
(the plugin used for components) won't allow for omitting attributes - it errors out because you're trying to use an undefined variable.
To work around it you'd need to make sure the variable isn't undefined
:
<if condition="typeof category !== 'undefined'">
{{ category}}
</if>
... or in an expression:
Category: {{ typeof category !== 'undefined' ? category : 'Uncategorized' }}
I'll add it to the docs, just realized I forgot to:
https://maizzle.com/docs/components#variables
Added it to the documentation:
https://maizzle.com/docs/components#undefined-variables