Svelte 条件元素类报告为语法错误 [英] Svelte conditional element class reported as a syntax error
问题描述
我正在根据 if 块的 Svelte 指南制作一个 if
块一>.看起来很简单,但 Svelte 认为这是一个语法错误:
[!] (svelte plugin) ParseError: Unexpected character '#'公共\js\templates\works.html3:<div class="slides js_slides">4:{#each 作为工作,索引}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>
为什么 {#if index === currentIndex }
不被认为是有效的?如何在 Svelte 中执行条件?
我不能为每种可能的结果创建单独的class=
块,但这是大量的工作.
Blocks ({#if...
, {#each...
etc) can'不能在属性内部使用——它们只能定义标记的结构.
相反,约定是使用三元表达式...
<div class="js_slide{索引 === 当前索引 ?'选择':''}{索引 === 0 ?'第一的' : ''}><img src="/images/work/screenshots/{works[index].slug }-0.{works[index].imageExtension }"/>
...或使用助手:
<div class="js_slide {getClass(work, index, currentIndex)}"><img src="/images/work/screenshots/{works[index].slug }-0.{works[index].imageExtension }"/>
有些人喜欢做data-selected={index === currentIndex}
和data=first={index === 0}
和样式基于 [data-selected=true]
选择器.
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.
这篇关于Svelte 条件元素类报告为语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!