posthtml / posthtml-expressions

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

How to check if a variable is set? #124

Closed thewebartisan7 closed 1 year ago

thewebartisan7 commented 2 years ago

Suppose we have a variable for set body class. In case we don't pass any variable as body class I get class="undefined"

How to check if variable is set?

Like:

<body class="{{ if(bodyClass) bodyClass }}">
or
<body class="{{ bodyClass ? bodyClass : 'default' }}">
Scrum commented 2 years ago

Now you'd better resort to constructing https://github.com/posthtml/posthtml-expressions#conditionaltags. In the future, I'll see what can be done for such expressions. Thank you for bringing this to our attention.

thewebartisan7 commented 2 years ago

Thanks. I already saw conditional tags, however it's messed to do this for every variable, like html dir attribute, head title tag, several classes, etc.

cossssmin commented 2 years ago

Same as your other examples:

<body class="{{ bodyClass || 'default' }}">

Where 'default' can be an empty string '' in order to output <body class="">.

thewebartisan7 commented 2 years ago

Same as your other examples:

<body class="{{ bodyClass || 'default' }}">

Where 'default' can be an empty string '' in order to output <body class="">.

Thanks for your reply. I have already try this, but this works only when bodyClass is defined, even empty.

When it's not defined, the output is like not compiled, example:

{{ bodyClass || 'default' }} 

Or sometimes even there is error undefined variable.

thewebartisan7 commented 2 years ago

Component:

<div class="{{ maybeUndefined || 'is undefined' }}">
  {{ maybeUndefined || 'is undefined' }}
</div>

Usage:

<h1>test2</h1>

<include src="components/test.html"></include>

Output:

Screenshot 2022-04-27 at 09 34 33
thewebartisan7 commented 2 years ago

I found a way to handle this:

<body class="{{ typeof bodyClass !== 'undefined' ? bodyClass : 'default' }}">