Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 35 ยท Templates and Markup

Text, Expressions and Attributes

Put JavaScript into Svelte markup: text expressions, dynamic attributes, shorthand, spread, class and style directives, and {@html} safety.

Svelte markup is HTML with curly braces. Inside { } you can write any single JavaScript expression, and the compiler keeps the result in sync with the state it reads. This lesson covers the building blocks you will use in every component: text, attributes, classes, styles and raw HTML.

Text expressions

SVELTE
<script>
  let name = $state('Ada');
  let a = $state(6);
  let b = $state(7);
</script>

<h1>Hello {name.toUpperCase()}!</h1>
<p>{a} times {b} is {a * b}</p>
<p>{a > b ? 'a is bigger' : 'b is bigger or equal'}</p>

Only expressions work, not statements: no if, for or let inside braces. Use blocks for those. To print a literal brace, write &lbrace; and &rbrace;, or use {'{'}.

Text is always escaped: if name contains <b>, the user sees the characters, not bold text. That protects you from cross-site scripting by default.

Dynamic attributes

Use braces as the attribute value:

SVELTE
<script>
  let src = $state('/samples/sunset.svg');
  let label = $state('A sunset');
  let disabled = $state(false);
</script>

<img {src} alt={label} />
<button {disabled}>Save</button>
<a href="/profile/{userId}">Profile</a>

Details worth knowing:

  • Shorthand: means src={src}.
  • Mixed text and expressions: href="/profile/{userId}" builds a string.
  • Booleans: disabled={false} removes the attribute; disabled={true} adds it.
  • null/undefined: the attribute is removed.

Spread attributes

When you have an object of attributes, spread it:

SVELTE
<script>
  const props = { id: 'main', 'aria-label': 'Search', placeholder: 'Type here' };
</script>

<input {...props} />

Order matters: later attributes override earlier ones, so <input {...props} id="other" /> uses id="other".

Event attributes

Events in Svelte 5 are regular attributes named onclick, oninput, onkeydown, and so on:

SVELTE
<button onclick={() => alert('Hi')}>Greet</button>
<input oninput={(event) => (text = event.currentTarget.value)} />

The old on:click directive still works but is deprecated. Events get their own lesson: Events and Bindings.

Classes

You can write ordinary strings:

SVELTE
<div class="card {big ? 'big' : ''}">...</div>

For toggling, Svelte offers two ergonomic options. The class: directive:

SVELTE
<li class:done class:selected={index === current}>{text}</li>

and, in current Svelte 5 versions, class accepts objects and arrays (clsx-style):

SVELTE
<li class={['item', { done, selected: index === current }]}>{text}</li>

Falsy entries are dropped and truthy object keys are kept. This is cleaner when many classes depend on conditions.

Styles

Use the style: directive to set one property at a time, optionally with a modifier for !important:

SVELTE
<div style:color={color} style:width="{size}px" style:--accent={accent}>
  Box
</div>

style:--accent sets a CSS custom property, a good way to pass colors from a parent into scoped styles.

Raw HTML with {@html}

To insert HTML from a string, use {@html ...}:

SVELTE
<article>{@html post.bodyHtml}</article>

{@html} does not escape or sanitize. Never use it with user-provided text unless you have sanitized it with a trusted library. Prefer normal output, which is always safe.

Also note that scoped styles do not reach inside {@html} content. Use :global selectors for it.

Constants with {@const}

Inside a block you can name an intermediate value with {@const}:

SVELTE
{#each boxes as box}
  {@const area = box.width * box.height}
  <p>{box.width} x {box.height} = {area}</p>
{/each}

Debugging with {@debug}

{@debug name} logs the value whenever it changes and pauses if devtools are open. Remove it before shipping.

Stand-in: rendering expressions

This stand-in implements the core of text and attribute rendering: { } placeholders are evaluated against a state object, values are HTML-escaped, and boolean attributes are removed when false. Because this runs plain JavaScript, it can show the same rules you just read.

JS Escaping and attribute rules (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The <b> tags came out as &lt;b&gt;, the escaped text that shows as characters in a browser.

Class and style toggling (stand-in page)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is allowed inside { } in markup?

    Braces hold expressions only. Statements need blocks such as {#if} and {#each}.
  2. 2. What does <img {src} alt={label} /> use for {src}?

    When the attribute name and variable are the same, the shorthand is allowed.
  3. 3. What happens to text output with {userInput} when it contains <script>?

    Normal expressions are escaped. Only {@html} inserts raw HTML.
  4. 4. When is {@html} acceptable?

    It skips escaping, so unsanitized user input would be an XSS hole.
  5. 5. What does style:--accent={accent} do?

    The style: directive can set normal properties and CSS custom properties.

Summary

  • prints escaped text; attributes accept expressions, shorthand and spread.
  • Boolean attributes are added or removed; null/undefined removes an attribute.
  • Event handlers are attributes such as onclick={...} in Svelte 5.
  • Use class:name, class objects/arrays and style:prop for conditional styling.
  • {@html} is raw and unsafe with untrusted input; {@const} names intermediate values.

Next: Conditional Rendering with {#if}