Skip to content

Feature request: aliasing to a variable using as in #if statements and similar ones #21

@pepkin88

Description

@pepkin88

Analogously to #each blocks, #ifs could also use the as keyword to store the evaluated condition expression to a variable:

{#if some.long || or.dynamic().expression as value}
  <div>
    Single usage inside a wrapping element: {value}
    Possible multiple usages, but with only one evaluation: {value}
  </div>
{/if}

Ideally I'd like to access the condition with a standardized keyword, like this. I emulated something like that in Handlebars by creating a custom #v helper, and I am using it quite often in my codebase.
It looks like this:

{{#v (some long (and 'complex' expression))}}
  I can then use the value like this: {{@v}}. The block gets rendered only if the value is truthy.
{{else}}
  If the value is falsy, I can (optionally) include an else block.
{{/v}}

I can see that Svelte (and HTMLx) opts for the explicit variable names, like in the #each case, where in HTMLx you explicitly declare variables for the iterated value and index, where in Handlebars it is optional, because by default they have their hierarchical context system for that.
I can respect that. That's why I think that using the existing as keyword could serve an acceptable compromise for the use case of aliasing the evaluated condition's value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions