I am making an if
block per the Svelte Guide for if blocks. It seems simple enough, but Svelte thinks it's a syntax error:
[!] (svelte plugin) ParseError: Unexpected character '#'
public\js\templates\works.html
3: <div class="slides js_slides">
4: {#each works as work, index}
5: <div class="js_slide {#if index === currentIndex }selected{/if} {#if index === 0 }first{/if}">
^
6: <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
7: </div>
Why isn't {#if index === currentIndex }
considered valid? How can I do a conditional in Svelte?
Not I could create seperate class=
blocks for every possible outcome, but that's a massive amount of work.
Blocks ({#if...
, {#each...
etc) can't be used inside attributes — they can only define the structure of your markup.
Instead, the convention is to use ternary expressions...
<div class="
js_slide
{index === currentIndex ? 'selected' : ''}
{index === 0 ? 'first' : ''}
">
<img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
</div>
...or to use a helper:
<!-- language: lang-html -->
<div class="js_slide {getClass(work, index, currentIndex)}">
<img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
</div>
Some people prefer to do things like data-selected={index === currentIndex}
and data=first={index === 0}
, and style based on [data-selected=true]
selectors instead.
Since Svelte 2.13 you can also do
<div class:selected={index === currentIndex}>...</div>
See https://svelte.dev/docs#class_name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With