if/else condition with local variable inside component not working
- Maizzle Version: 3.3.0
- Node.js Version: 14.9.0
Sample code
<!-- template: myemail.html -->
---
articles:
-
title: "Article 1"
description: ""
-
title: "Article 2"
description: "description"
---
<each loop="article in page.articles">
<!-- this works -->
<p>{{article.title}}</p>
<p>
<if condition="article.description">has description</if>
<else>no description</else>
</p>
<!-- duplicating above inside a component -->
<component src="article_preview.html" locals='{
"title": "{{article.title}}",
"description": "{{article.description}}"
}'></component>
</each>
<!-- component: article_preview.html -->
<p>{{title}}</p> <!-- this works -->
<p>{{description}}</p> <!-- this works. It's "" (1) or "description" (2) -->
<!-- The condition is always true -->
<p>
<if condition="description">has description</if>
<else>no description</else>
</p>
<!-- This breaks the build: 'ReferenceError: article is not defined' -->
<p>
<if condition="description">{{description}}</if>
</p>
Issue 1
Using <if condition="foo">testing foo</if> in a component, where foo is a local variable
condition="foo" → always true even when foo is undefined or empty string
condition="foo == undefined" → always false
condition="foo == 'undefined'" → always false
condition="foo == 'bar'" (knowing foo is 'bar') → always false
Issue 2
Specific to when component is loaded inside an each loop.
Using {{foo}} inside <if></if> in a component
<if condition="foo">{{foo}}</if>
breaks the build
✖ Failed to compile template: myemail.html
⚠ ReferenceError: article is not defined
Probably related to https://github.com/maizzle/framework/issues/397
FYI, using a switch statement will also lead to issue 1. Unfortunately, reverting to 3.1.3 didn't fix that issue... Reproductible here
Here's a workaround that I've been testing:
- In your html, omit the
fooproperty entirely (rather than set an empty string) - Use a
typeofswitch in your component:
<!-- component-->
<switch expression="typeof foo">
<case n="'undefined'"> // note the triple quotes
Default value if undefined
</case>
<default>
{{foo}}
</default>
</switch>
Please see this comment: https://github.com/maizzle/framework/issues/397#issuecomment-1083181684
In the latest alpha (currently v4.0.0-alpha.7) there is now a way to pass in loop variables to be evaluated.
Tested and works fine in latest alpha (v4.0.0-alpha.8), you'll need to use expressions passed through attributes to the component like so:
---
articles:
-
title: "Article 1"
description: ""
-
title: "Article 2"
description: "description"
---
<each loop="article in page.articles">
<component
src="article_preview.html"
title="{{ article.title }}"
description="{{ article.description }}"
></component>
</each>