Svelte in markdown
This feature allows you to write <style>, #if, <script>, <script module> #each, #await, #snippet, @render @html, @const, <svelte:xxx>' in .md files
Basic
Here's a basic example with #if, #each, #await, @html, @const
- 1: foo
- 2: bar
- 3: zoo
Fail
Promise Failed!
Content render with @html
<script>
let count = $state(0)
const items = ['foo', 'bar', 'zoo']
let boolVal = $state(false)
const promisePass = () => new Promise(resolve => {
setTimeout(() => {
resolve('Promise Passed!')
}, 2000)
})
const promiseFail = () => new Promise((_, reject) => {
setTimeout(() => {
reject('Promise Failed!')
}, 2000)
})
let promise = $derived(boolVal ? promisePass() : promiseFail())
</script>
<ul>
{#each items as item, i}
{@const str = `${i + 1}: ${item}`}
<li>
{str}
</li>
{/each}
</ul>
<button onclick="{() => boolVal = !boolVal}">
Toggle
</button>
{#if boolVal}
<h3 class="text-green">
Pass
</h3>
{:else}
<h3 class="text-red">
Fail
</h3>
{/if}
{#await promise}
<h3 class="text-orange">
Loading
</h3>
{:then res}
<h3 class="text-green">
{res}
</h3>
{:catch err}
<h3 class="text-red">
{err}
</h3>
{/await}
{@html "<h1>Content render with @html</h1>"} md
Click fold/expand code
Syntax Restrictions
Always use quotes in markdown files.
-
+
<script>
let count = $state(0)
</script>
<button onclick={() => count++}></button>
<button onclick="{() => count++}"></button> md
Or you can wrap it with a div
-
+
+
+
<script>
let count = $state(0)
</script>
<button onclick={() => count++}></button>
<div>
<button onclick={() => count++}></button>
</div> md
A Counter
Output
Input
A counter