alpinejs / alpine

A rugged, minimal framework for composing JavaScript behavior in your markup.
https://alpinejs.dev
MIT License
28.29k stars 1.23k forks source link

Add x-else and x-else-if Directives for Conditional Rendering #4353

Open mvaliolahi opened 2 months ago

mvaliolahi commented 2 months ago

This pull request adds two new directives, x-else and x-else-if, to Alpine.js.

How It Works:

x-else-if: Looks for a preceding x-if or x-else-if and only shows its content if none of those conditions are true. x-else: Displays its content only if all previous conditions have failed.

Basic Usage:

<div x-data="{ value: 2 }">
    <template x-if="value === 1">
        <h1>Value is 1</h1>
    </template>
    <template x-else-if="value === 2">
        <h2>Value is 2</h2>
    </template>
    <template x-else-if="value === 3">
        <h3>Value is 3</h3>
    </template>
    <template x-else>
        <h4>Value is unknown</h4>
    </template>
</div>

Inside a Loop:

<div x-data="{ items: [{id: 1, value: 1}, {id: 2, value: 2}, {id: 3, value: 3}, {id: 4, value: 4}] }">
    <template x-for="item in items" :key="item.id">
        <div>
            <template x-if="item.value === 1">
                <span>Item <span x-text="item.id"></span>: Value is 1</span>
            </template>
            <template x-else-if="item.value === 2">
                <span>Item <span x-text="item.id"></span>: Value is 2</span>
            </template>
            <template x-else-if="item.value === 3">
                <span>Item <span x-text="item.id"></span>: Value is 3</span>
            </template>
            <template x-else>
                <span>Item <span x-text="item.id"></span>: Value is unknown</span>
            </template>
        </div>
    </template>
</div>

Tests:

I've added tests to ensure these new directives work as expected, including cases with multiple conditions and inside x-for loops.

Why This Matters:

This enhancement provides more flexibility for conditional logic, allowing you to handle complex scenarios directly within your templates.

ekwoka commented 2 months ago

There's some cases not covered in the code and tests

https://github.com/mvaliolahi/alpine/pull/1

Made a PR to add these tests.

Specifically:

This is a great feature to have, so kudos for stepping up to do it!

I don't think this isn't a great way to go about it though.

Maybe have the initial x-if walk forward through the DOM to identify the branches and control who should show.

mvaliolahi commented 2 months ago

@ekwoka I think your concerns are valid I will change the code to support this case.