Skip to content

Conditionally place default slot #2006

@iamdadmin

Description

@iamdadmin

Tempest version

3.x-dev

PHP version

8.5

Operating system

Linux

Description

Consider this view component x-link.view.php I want it to render a button when no href is passed ($to prop) but we can't render the token dynamically here, so I put in an if to conditionally render the appropriate tag. But then I cannot nest the <x-slot /> within an if.

<a 
    :if="isset($to) && $to != ''"
    :href="($disabled ?? false) ? '' : $to"
    :aria-disabled="($disabled ?? false) ? 'true' : ''"
    :role="($disabled ?? false) ? 'link' : ''"
    :disabled="$disabled ?? ''"
    :rel="$rel ?? (str_contains($to, '://') ? 'noopener noreferrer' : '')"
    :target="$target ?? (str_contains($to, '://') ? '_blank' : '')"
    :up-toggle="$toggle ?? ''"
    :class="$class ?? ''"
><x-slot /></a>
<button
    :else
    :disabled="$disabled ?? ''"
    :up-toggle="$toggle ?? ''"
    :class="$class ?? ''"
><x-slot /></button>

I only need the one slot, the other code won't be rendered.

I also tried using an expression to define the name as either Slot::DEFAULT or 'unused' depending on the same if conditions, but that didn't create the default slot at all, i.e.

<a 
    :if="isset($to) && $to != ''"
    :href="($disabled ?? false) ? '' : $to"
    :aria-disabled="($disabled ?? false) ? 'true' : ''"
    :role="($disabled ?? false) ? 'link' : ''"
    :disabled="$disabled ?? ''"
    :rel="$rel ?? (str_contains($to, '://') ? 'noopener noreferrer' : '')"
    :target="$target ?? (str_contains($to, '://') ? '_blank' : '')"
    :up-toggle="$toggle ?? ''"
    :class="$class ?? ''"
><x-slot :name="isset($to) && $to != '' ? Slot::DEFAULT : 'unused'" /></a>
<button
    :else
    :disabled="$disabled ?? ''"
    :up-toggle="$toggle ?? ''"
    :class="$class ?? ''"
><x-slot :name="!isset($to) ? Slot::DEFAULT : 'unused'" /></button>

I could also make both named slots, and pass the appropriate slot in everywhere I consume it, that will add code elsewhere but is doable? I'm gonna try it now, but I think supporting conditional default slot makes sense?

Edit: tried to do this in the upstream, :name isn't eval'd on x-slot it seems, I probably should've checked the code before attempting but figured this was faster.

<x-slot :name="isset($to) && $to != '' ? 'a' : 'button'">

Errors :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions