posthtml / posthtml-expressions

Use variables, JS-like expressions, and even markup-powered logic in your HTML.
Other
123 stars 20 forks source link

Conditionals within loops #57

Closed kieranpotts closed 5 years ago

kieranpotts commented 5 years ago

Problem

I would like to be able to use conditionals within loops, where the conditional expression evaluates against another local template variable.

Details

Input:

posthtml([
  /* Some other plugins */
  expressions({
    locals: {
      pages: [
        { path: "/page1", title: "Page 2" },
        { path: "/page2", title: "Page 2" },
        { path: "/page3", title: "Page 3" }
      ],
      current_path: '/page1'
    }
  })
])
/* process(), then(), etc. */
<each loop="page in pages">
    <if condition="page.path === current_path">
        <a class="selected" href="{{ page.path }}">{{ page.title }}</a>
    </if>
    <else>
        <a href="{{ page.path }}">{{ page.title }}</a>
    </else>
</each>

Desired output:

<a class="selected" href="/page1">Page 1</a>
<a href="/page2">Page 2</a>
<a href="/page3">Page 3</a>

Actual output:

ReferenceError: current_path is not defined

Thus the expression page.path === current_path does not evaluate current_path to a template variable.

Is this expected behaviour? If not, could it be considered by the project maintainers as a feature enhancement? (I may be able to contribute the necessary source code changes as a PR.)

Thank you.

Environment

OS Node npm PostHTML
Windows 10 10.15.3 6.4.1 1.1.0
Scrum commented 5 years ago

@kieranpotts Hi, thanks for your feedback - this is very important to us. I will try to deal with this problem as soon as possible.

Scrum commented 5 years ago

@kieranpotts I updated all the dependencies and wrote a test case for your case, now everything should work

kieranpotts commented 5 years ago

It works! Fantastic, thank you so much @Scrum :)