posthtml / posthtml-expressions

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

Check if key exists in locals #102

Closed BjornDCode closed 3 years ago

BjornDCode commented 4 years ago

Problem

It's not currently possible to have a conditional that checks whether a key is set in the locals object.

This is an expansion to #79

Details

I have a use case where the contents of the locals object is dynamic. It's read from front-matter from a markdown file. I would like to be able to check whether the key is set in the locals object and then output the value if it does.

Front matter:

---
skeleton: base.html
title: My First Post
category: 'Cool category'
---

Which is parsed into the following object:

{
    skeleton: 'base.html',
    title: 'My First Post',
    category: 'Cool category',
}

If I for example don't include category in the front-matter then the object would look like the following:

{
    skeleton: 'base.html',
    title: 'My First Post',
}

In the HTML template it's not currently possible to check whether category exists:

<if condition="category">
    <p>In: {{ category }}</p>
</if>

It throws the following error:

UnhandledPromiseRejectionWarning: ReferenceError: category is not defined

I've tried the following as well:

<if condition="{{ category }}">
    <p>In: {{ category }}</p>
</if>

Which throws the same error as in #101

Error Logs

The full error:

(node:99739) UnhandledPromiseRejectionWarning: ReferenceError: category is not defined
(node:99739) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
Scrum commented 4 years ago

@BjornDCode use the option strictMode with value false to suppress mistakes

cossssmin commented 3 years ago

@Scrum this still throws a ReferenceError:

<if condition="key_not_exists">
  {{ key_not_exists.foo }}
  it works!
</if>

Result:

Rejected promise returned by test. Reason:

ReferenceError {
  message: 'key_not_exists is not defined',
}

Originally reported in maizzle/framework#354

Scrum commented 3 years ago

Hi have you used this parameter? https://github.com/posthtml/posthtml-expressions/issues/102#issuecomment-719518146

cossssmin commented 3 years ago

I was using it, yes. It works in 1.6.1 now, thanks!