Index of every page on this site: llms.txt
All skills
spences10 avatar

/svelte-template-directives

@5fe4989
Run it yourself

Svelte template directives ({@attach}, {@html}, {@render}, {@const}, {@debug}). Use for DOM manipulation, third-party libs, tooltips, canvas, dynamic HTML. @attach replaces use: actions.

Use this Skill: https://skilld.dev/gh/spences10/svelte-skills-kit/svelte-template-directives

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesother-directives.md

≈1.2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Other Template Directives

{@html ...}

Renders raw HTML strings. Use with caution - never render untrusted content.

<script>
	let htmlContent = '<strong>Bold</strong> and <em>italic</em>';
</script>

{@html htmlContent}

Security Warning

Always sanitize user-provided HTML:

<script>
	import DOMPurify from 'dompurify';

	let userContent = $state('');
	const sanitized = $derived(DOMPurify.sanitize(userContent));
</script>

{@html sanitized}

Common Use Cases

  • Rendering markdown converted to HTML
  • CMS content with formatting
  • Syntax-highlighted code blocks

{@render ...}

Renders snippets - Svelte 5's replacement for slots.

<script>
	let { header, children } = $props();
</script>

<div class="card">
	{#if header}
		<header>{@render header()}</header>
	{/if}
	<main>{@render children?.()}</main>
</div>

With Parameters

Snippets can receive parameters:

<script>
	let { row } = $props();
	let items = $state([{ name: 'Apple' }, { name: 'Banana' }]);
</script>

{#each items as item}
	{@render row(item)}
{/each}
<!-- Usage -->
<List>
	{#snippet row(item)}
		<li>{item.name}</li>
	{/snippet}
</List>

Optional Snippets

Use optional chaining for optional snippets:

{@render footer?.()}

{@const ...}

Declares local constants within template blocks. Useful in {#each} and {#if}.

{#each items as item}
	{@const fullName = `${item.firstName} ${item.lastName}`}
	{@const isLongName = fullName.length > 20}

	<div class:truncate={isLongName}>
		{fullName}
	</div>
{/each}

Why Use @const?

  • Avoids recalculating values multiple times in a block
  • Makes complex expressions more readable
  • Scoped to the block - doesn't pollute component scope

{@debug ...}

Pauses execution and opens devtools when specified values change.

<script>
	let count = $state(0);
	let items = $state([]);
</script>

{@debug count, items}

<button onclick={() => count++}>Increment</button>

Tips

  • Remove {@debug} before production
  • Use with specific variables, not entire objects
  • Combine with browser devtools for best debugging experience

Debug Without Variables

{@debug}

Pauses on every update (rarely useful, but available).

Keyed Each Blocks

Per official Svelte best practices: always use keyed each blocks for better performance.

Basic Keyed Each

{#each items as item (item.id)}
	<div>{item.name}</div>
{/each}

Key must uniquely identify the object. Do NOT use the index:

<!-- WRONG - index as key -->
{#each items as item, i (i)}
	<div>{item.name}</div>
{/each}

<!-- RIGHT - unique identifier -->
{#each items as item (item.id)}
	<div>{item.name}</div>
{/each}

Why Keys Matter

Without keys, Svelte updates existing DOM nodes in place when the array changes. With keys, Svelte can surgically insert, remove, or reorder items instead.

Without key: Removing item 2 from [A, B, C] updates node 2 to show C's data and removes the last node.

With key: Removing item B actually removes B's DOM node, leaving A and C untouched.

Avoid Destructuring with bind

Per best practices: avoid destructuring if you need to mutate the item.

<!-- WRONG - destructured value is disconnected from original -->
{#each items as { count } (item.id)}
	<input bind:value={count} /> <!-- Won't update the original item -->
{/each}

<!-- RIGHT - reference the item directly -->
{#each items as item (item.id)}
	<input bind:value={item.count} /> <!-- Updates the original -->
{/each}

Window and Document Events

Per official best practices: use <svelte:window> and <svelte:document> for window/document event listeners. Avoid onMount or $effect for this.

<svelte:window onkeydown={handleKeydown} onscroll={handleScroll} />
<svelte:document onvisibilitychange={handleVisibility} />

Common Events

<!-- Keyboard shortcuts -->
<svelte:window onkeydown={(e) => {
	if (e.key === 'Escape') closeModal();
	if (e.ctrlKey && e.key === 's') { e.preventDefault(); save(); }
}} />

<!-- Online/offline detection -->
<svelte:window ononline={() => status = 'online'} onoffline={() => status = 'offline'} />

<!-- Responsive design -->
<svelte:window
	bind:innerWidth={width}
	bind:innerHeight={height}
/>

Bindable Window Properties

<svelte:window
	bind:innerWidth
	bind:innerHeight
	bind:scrollX
	bind:scrollY
	bind:online
/>

Why not $effect: <svelte:window> automatically cleans up listeners when the component is destroyed. No manual cleanup needed.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill is a technical reference guide for Svelte 5 template directives. It demonstrates security best practices by identifying potential risks associated with the raw HTML rendering directive and providing explicit instructions on how to use sanitization libraries like DOMPurify to mitigate those risks. No malicious intent, obfuscation, or unauthorized data access patterns were detected.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 5fe4989. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last month.

Steadyupdated 7 months ago

README badge

README badge for spences10/svelte-skills-kit/svelte-template-directives