Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte conditional element class reported as a syntax error

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.

like image 295
mikemaccana Avatar asked Jul 18 '18 09:07

mikemaccana


2 Answers

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.

like image 101
Rich Harris Avatar answered Nov 20 '22 21:11

Rich Harris


Since Svelte 2.13 you can also do

<div class:selected={index === currentIndex}>...</div>

See https://svelte.dev/docs#class_name

like image 44
oae Avatar answered Nov 20 '22 21:11

oae