@ if Inside of Classes

I would be really nice if we could put a @ if statement inside of the class area for an element, so we don’t have to build extra html for each condition.

Ex:
<div class="@if(somecheck1){{classesforcondition1}}@endif @if(somecheck2){{classesforcondition2}}@endif"></div>

This is already supported. The only “gotcha” is that @if statements do not support logic: so you can’t do @if(myControl == 'something').

If, however, you have a switch control you can do @if(mySwitchControl).

All logic must be placed in the Hooks, and you should send any variables to the template by using rw.setProps().

Example:

properties:

{
    "groups": [{
        "title": "Example",
        "properties": [{
            "title": "Text",
            "id": "textInput",
            "text": {}
        }]
    }]
}

Hooks:

const transformHook = (rw) => {
    const { textInput } = rw.props;

    const somethingIsTrue = textInput == 'something';

    rw.setProps({ somethingIsTrue });
}

exports.transformHook = transformHook;

Template

@if(somethingIsTrue)
This will be added if the textInput == 'something'
@endif
1 Like

While my previous response explained how you can achieve this, I’d like to offer a recommendation: rather than handling logic directly in the template, it’s better to manage as much logic as possible in the Hooks file.

This approach helps keep your template files cleaner and allows Elements to process components more efficiently. One of the primary reasons @if statements don’t support inline conditions is to avoid logic-heavy templates that slow down template processing.

In your example, you can handle the checks in the Hooks file and pass a single variable to the template for rendering. Here’s how you can do that:

Hooks:

const transformHook = (rw) => {
    const { someProperty } = rw.props;

    // Create a classes variable based on the logic
    const classes = someProperty 
        ? 'bg-green-500'  // classes when true
        : 'bg-red-500';   // classes when false

    // Pass the classes variable to the template
    rw.setProps({ classes });
};

exports.transformHook = transformHook;

Template:

<div class="{{classes}}">My Content</div>

Hope that helps! :slight_smile:

2 Likes