Svelte: {{#each ...}}...{{else}}...{{/each}}

Created on 1 Dec 2016  Â·  7Comments  Â·  Source: sveltejs/svelte

Suggestion via Twitter – an else block for the special case when your array is empty:

{{#each todos as todo}}
  <Todo description='{{todo.description}}' done='{{todo.done}}'/>
{{else}}
  <p>Nothing left to do! Congratulations, turn off your laptop and go outside</p>
{{/each}}
enhancement

Most helpful comment

Why not this?

{{#each todos as todo}}
  <Todo description='{{todo.description}}' done='{{todo.done}}'/>
{{empty}}
  <p>Nothing left to do! Congratulations, turn off your laptop and go outside</p>
{{/each}}

Laravel uses that syntax, https://laravel.com/docs/5.3/blade#loops.

All 7 comments

An else block that is related to iteration? I think that's kind of confusing!

I don't see anything wrong with this:

{{#each todos as todo}}
  <Todo description='{{todo.description}}' done='{{todo.done}}'/>
{{/each}}
{{#if todos.length === 0}}
  <p>Nothing left to do! Congratulations, turn off your laptop and go outside</p>
{{/if}}

Or this:

{{#if todos.length}}
  {{#each todos as todo}}
    <Todo description='{{todo.description}}' done='{{todo.done}}'/>
  {{/each}}
{{else}}
  <p>Nothing left to do! Congratulations, turn off your laptop and go outside</p>
{{/if}}

After all, this is the JavaScript way of doing it.

There is a lot of precedent in other template languages for having an else branch for iteration.

Sounds very convenient and the use-case is quite common, 1+ for each-else

In django, that cased is triggered in the empty clause of a for loop.

Why not this?

{{#each todos as todo}}
  <Todo description='{{todo.description}}' done='{{todo.done}}'/>
{{empty}}
  <p>Nothing left to do! Congratulations, turn off your laptop and go outside</p>
{{/each}}

Laravel uses that syntax, https://laravel.com/docs/5.3/blade#loops.

Each/else is a built in helper for Handlebars. http://handlebarsjs.com/builtin_helpers.html

needs documentation update in the example?

https://svelte.dev/examples#keyed-each-blocks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thoughtspile picture thoughtspile  Â·  3Comments

angelozehr picture angelozehr  Â·  3Comments

rob-balfre picture rob-balfre  Â·  3Comments

AntoninBeaufort picture AntoninBeaufort  Â·  3Comments

ricardobeat picture ricardobeat  Â·  3Comments