posthtml-expressions icon indicating copy to clipboard operation
posthtml-expressions copied to clipboard

How to check if a variable is set?

Open thewebartisan7 opened this issue 3 years ago • 6 comments

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' }}">

thewebartisan7 avatar Jan 21 '22 11:01 thewebartisan7

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.

Scrum avatar Jan 26 '22 06:01 Scrum

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.

thewebartisan7 avatar Jan 26 '22 08:01 thewebartisan7

Same as your other examples:

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

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

cossssmin avatar Apr 26 '22 11:04 cossssmin

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 avatar Apr 27 '22 07:04 thewebartisan7

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 avatar Apr 27 '22 07:04 thewebartisan7

I found a way to handle this:

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

thewebartisan7 avatar May 25 '22 17:05 thewebartisan7