mikemaccana
mikemaccana

Reputation: 123670

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.

Upvotes: 10

Views: 12943

Answers (3)

sk shahriar ahmed raka
sk shahriar ahmed raka

Reputation: 1179

As stated in https://svelte.dev/docs#class_name , it require extra JS variable to operate if else inside class

here is a example where a each loop iterate from a to b and when if is true the css will be applied

{#each Array.from(Array(b+1).keys()).slice(a) as i }

    <div class="{ i===4 ? "border-l-2 border-blue-500" : ""}  p-3 space-y-4">
     some sample text
    </div>
{/each}

example (1 to 15) :

{#each Array.from(Array(15+1).keys()).slice(1) as i }

    <div class="{ i===3 ? "border-l-2 border-blue-500" : ""}  p-3 space-y-4">
     some sample text
    </div>
{/each}

Upvotes: 0

oae
oae

Reputation: 1652

Since Svelte 2.13 you can also do

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

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

Upvotes: 10

Rich Harris
Rich Harris

Reputation: 29615

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.

Upvotes: 22

Related Questions