diff --git a/site/content/blog/2023-04-01-whats-new-in-svelte-april-2023.md b/site/content/blog/2023-04-01-whats-new-in-svelte-april-2023.md index 1e79a227ef6e..7849621d870c 100644 --- a/site/content/blog/2023-04-01-whats-new-in-svelte-april-2023.md +++ b/site/content/blog/2023-04-01-whats-new-in-svelte-april-2023.md @@ -1,6 +1,6 @@ --- title: "What's new in Svelte: April 2023" -description: "Loads of new Svelte compiler features, plus Svelte Summit and SvelteHack" +description: 'Loads of new Svelte compiler features, plus Svelte Summit and SvelteHack' author: Dani Sandoval authorURL: https://dreamindani.com --- @@ -14,6 +14,7 @@ Don't forget! Svelte Summit Spring, Svelte's 6th virtual conference, will be hap Now let's jump into this month's changes... ## What's new in Svelte + - A bunch of new features are now available as of **3.56.0**! - Add `|stopImmediatePropagation` event modifier for `on:eventname` ([#5085](https://github.com/sveltejs/svelte/issues/5085), [Docs](https://svelte.dev/docs#template-syntax-element-directives-on-eventname)) - Add `axis` parameter to `slide` transition ([#6182](https://github.com/sveltejs/svelte/issues/6182), [Docs](https://svelte.dev/docs#run-time-svelte-transition-slide)) @@ -31,15 +32,18 @@ Now let's jump into this month's changes... For all the changes to the Svelte compiler, including unreleased changes, check out the [CHANGELOG](https://github.com/sveltejs/svelte/blob/master/CHANGELOG.md). ## What's new in SvelteKit + - You can now get all cookies for a request with `cookies.getAll` (**1.10.0**, [#9287](https://github.com/sveltejs/kit/pull/9287), [Docs](https://kit.svelte.dev/docs/types#public-types-cookies)) - Easily manage the submission status of (multiple) forms with the new exposed `submitter` parameter in `use:enhance` (**1.12.0**, [#9425](https://github.com/sveltejs/kit/pull/9425), [Docs](https://kit.svelte.dev/docs/types#public-types-submitfunction)) - The default error page now has dark mode styles (**1.13.0**, [#9460](https://github.com/sveltejs/kit/pull/9460)) - You can now omit types on all methods and variables with special meaning to SvelteKit and still benefit from full type safety! Read more about it in the [announcement blog post](https://svelte.dev/blog/zero-config-type-safety) + --- ## Community Showcase **Apps & Sites built with Svelte** + - [Peerbeer](https://peer.beer/) lets you share files peer-to-peer (p2p) without any third parties or data limits - [unplaneted](https://unplaneted.com/) is an interface for exploring very large space images - [PokeBook](https://github.com/pokegh0st/pokebook) is a digital notebook for writing poetry that provides a beautiful distraction-free environment and autosave @@ -55,6 +59,7 @@ For all the changes to the Svelte compiler, including unreleased changes, check **Learning Resources** _Featuring Svelte Contributors and Ambassadors_ + - [Streaming, snapshots, and other new features since SvelteKit 1.0](https://svelte.dev/blog/streaming-snapshots-sveltekit) by Geoff Rich on the svelte.dev Blog - [Dev Vlog: Rich Harris shows us what's new in Svelte and Kit, March 2023](https://www.youtube.com/watch?v=vgXgex5E-8g) from Svelte Society - If you missed this one live, check out [the next one](https://www.youtube.com/watch?v=MJHO6FSioPI) - scheduled for April 5th @@ -71,13 +76,14 @@ _Featuring Svelte Contributors and Ambassadors_ - [2023 March 23 - SvelteKit 1.13.0, Vitest and Playwright overview](https://www.youtube.com/watch?v=vpbhsbg2otg) _To Watch or Hear_ + - [Full Stack SvelteKit App Deployment Using Vercel And Supabase For $0](https://www.youtube.com/watch?v=uAF4Yd-gddo) by Joy of Code - [Why Is Svelte.js so Popular?](https://www.youtube.com/watch?v=73Y8Yyg54zc) by Prismic - [Interactive Tables in SvelteKit with TanStack Table](https://www.youtube.com/watch?v=-Zuo3UWjjI8) by hartenfellerdev - [SvelteKit + GraphQL with Houdini](https://www.youtube.com/watch?v=ADnaRwQZfqw&list=PLm0ILX0LGQk_220vvpsbyXH2VesRlCm-E) by Aftab Alam - _To Read_ + - [Thoughts on Svelte](https://tyhopp.com/notes/thoughts-on-svelte) by Ty Hopp - [Storybook](https://storybook.js.org/blog/storybook-for-sveltekit/) on why (and how) it supports SvelteKit - [Svelte Authentication Tutorial with Authorizer](https://thethinks.vercel.app/blog/svelte-authorizer) by The Thinks @@ -89,18 +95,19 @@ _To Read_ - [Secure Authentication in Svelte using Hooks](https://dev.to/brewhousedigital/secure-authentication-in-svelte-using-hooks-k5j) by Brewhouse Digital **Libraries, Tools & Components** + - [@vavite/node-loader](https://github.com/cyco130/vavite/tree/main/packages/node-loader) is a Node ESM loader that uses Vite to transpile modules to enable sourcemap and breakpoints support in SvelteKit (or any Vite) project - [Inlang](https://github.com/inlang/inlang) is building i18n for SvelteKit and is [looking for feedback](https://www.reddit.com/r/sveltejs/comments/11ydtui/sveltekit_and_i18n_lets_finally_solve_this_never/) - [Skeleton](https://www.skeleton.dev/) - the UI toolkit for Svelte and Tailwind - is now 1.0 πŸŽ‰ - [SvelteKit-integrated-WebSocket](https://github.com/suhaildawood/SvelteKit-integrated-WebSocket) provides first-class support for WebSockets within SvelteKit by attaching a WebSocket server to the global state -- [Svelte Legos](https://github.com/ankurrsinghal/svelte-legos) is a collection of essential Svelte Composition Utilities +- [Svelte Legos](https://github.com/ankurrsinghal/svelte-legos) is a collection of essential Svelte Composition Utilities - [svelte-stored-writable](https://github.com/efstajas/svelte-stored-writable) is a drop-in extension of Svelte's writable that additionally stores and restores its contents using localStorage. - [svelte-virtual](https://github.com/ghostebony/svelte-virtual) provides Svelte components for efficiently rendering large lists. - ChatGPT Clones and Starters - [chatwithme.chat](https://github.com/kierangilliam/chatwithme.chat) is an open source ChatGPT UI - [SlickGPT](https://github.com/ShipBit/slickgpt) is a light-weight "use-your-own-API-key" web client for the OpenAI API written in Svelte - [AI Chat Bestie](https://github.com/KTruong008/aichatbestie) is an unofficial ChatGPT app - - [chatgpt-svelte](https://github.com/ichbtrv/chatgpt-svelte) is a simple UI for the ChatGPT Open AI API + - [chatgpt-svelte](https://github.com/ichbtrv/chatgpt-svelte) is a simple UI for the ChatGPT Open AI API Thanks for reading! And don't forget to try your hand at the [Svelte Hackathon](https://hack.sveltesociety.dev/) πŸ§‘β€πŸ’» diff --git a/site/content/docs/00-introduction.md b/site/content/docs/00-introduction.md deleted file mode 100644 index 11f82117e9fc..000000000000 --- a/site/content/docs/00-introduction.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Before we begin ---- - -This page contains detailed API reference documentation. It's intended to be a resource for people who already have some familiarity with Svelte. - -If that's not you (yet), you may prefer to visit the [interactive tutorial](/tutorial) or the [examples](/examples) before consulting this reference. - -Don't be shy about asking for help in the [Discord chatroom](https://svelte.dev/chat). - -Using an older version of Svelte? Have a look at the [v2 docs](https://v2.svelte.dev). diff --git a/site/content/docs/01-getting-started.md b/site/content/docs/01-getting-started.md deleted file mode 100644 index 753f571ebb97..000000000000 --- a/site/content/docs/01-getting-started.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Getting started ---- - ---- - -To try Svelte in an interactive online environment you can try [the REPL](https://svelte.dev/repl) or [StackBlitz](https://node.new/svelte). - -To create a project locally we recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team: - -``` -npm create svelte@latest myapp -cd myapp -npm install -npm run dev -``` - -SvelteKit will handle calling [the Svelte compiler](https://www.npmjs.com/package/svelte) to convert your `.svelte` files into `.js` files that create the DOM and `.css` files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, and deployment. [SvelteKit](https://kit.svelte.dev/) utilizes [Vite](https://vitejs.dev/) to build your code and handle server-side rendering (SSR). There are [plugins for all the major web bundlers](https://sveltesociety.dev/tools#bundling) to handle Svelte compilation, which will output `.js` and `.css` that you can insert into your HTML, but most others won't handle SSR. - -If you don't need a full-fledged app framework and instead want to build a simple frontend-only site/app, you can also use Svelte (without Kit) with Vite by running `npm init vite` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS and CSS files inside the `dist` directory. - -The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and there are integrations with various other [editors](https://sveltesociety.dev/tools#editor-support) and tools as well. - -If you're having trouble, get help on [Discord](https://svelte.dev/chat) or [StackOverflow](https://stackoverflow.com/questions/tagged/svelte). diff --git a/site/content/docs/01-getting-started/01-introduction.md b/site/content/docs/01-getting-started/01-introduction.md new file mode 100644 index 000000000000..99ecdcb14336 --- /dev/null +++ b/site/content/docs/01-getting-started/01-introduction.md @@ -0,0 +1,49 @@ +--- +title: Introduction +--- + +Welcome to Svelte docs. These are for folks who are already familiar with Svelte and want to learn more about the details of how it works. + +If that's not you (yet), you may prefer to visit the [interactive tutorial](/tutorial) or the [examples](/examples) before consulting this reference. + +Don't be shy about asking for help in the [Discord chatroom](https://svelte.dev/chat). + +Using an older version of Svelte? Have a look at the [v2 docs](https://v2.svelte.dev). + +## Start a new project + +To try Svelte in an interactive online environment you can try [the REPL](https://svelte.dev/repl) or [StackBlitz](https://node.new/svelte). + +To create a project locally we recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team: + +``` +npm create svelte@latest myapp +cd myapp +npm install +npm run dev +``` + +SvelteKit will handle calling [the Svelte compiler](https://www.npmjs.com/package/svelte) to convert your `.svelte` files into `.js` files that create the DOM and `.css` files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, and deployment. [SvelteKit](https://kit.svelte.dev/) utilizes [Vite](https://vitejs.dev/) to build your code and handle server-side rendering (SSR). There are [plugins for all the major web bundlers](https://sveltesociety.dev/tools#bundling) to handle Svelte compilation, which will output `.js` and `.css` that you can insert into your HTML, but most others won't handle SSR. + +### Alternatives to SvelteKit + +If you don't need a full-fledged app framework and instead want to build a simple frontend-only site/app, you can also use Svelte (without Kit) with Vite by running `npm init vite` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS and CSS files inside the `dist` directory. + +Notable Mentions: + +- [Routify](https://www.routify.dev/) +- [Elder.js](https://elderjs.com/) + +## Differences from SvelteKit + +Svelte renders UI components. You can compose these components and render an entire page with just Svelte, but you need more than just Svelte to write an entire app. + +SvelteKit provides basic functionality like a [router](https://kit.svelte.dev/glossary#routing) β€” which updates the UI when a link is clicked β€” and [server-side rendering (SSR)](https://kit.svelte.dev/glossary#ssr). But beyond that, building an app with all the modern best practices is fiendishly complicated. Those practices include [build optimizations](https://vitejs.dev/guide/features.html#build-optimizations), so that you load only the minimal required code; [offline support](https://kit.svelte.devservice-workers); [preloading](https://kit.svelte.dev/link-options#data-sveltekit-preload-data) pages before the user initiates navigation; [configurable rendering](https://kit.svelte.dev/page-options) that allows you to render different parts of your app on the server with [SSR](https://kit.svelte.dev/glossary#ssr), in the browser [client-side rendering](https://kit.svelte.dev/glossary#csr), or at build-time with [prerendering](https://kit.svelte.dev/glossary#prerendering); and many other things. SvelteKit does all the boring stuff for you so that you can get on with the creative part. + +It reflects changes to your code in the browser instantly to provide a lightning-fast and feature-rich development experience by leveraging [Vite](https://vitejs.dev/) with a [Svelte plugin](https://github.com/sveltejs/vite-plugin-svelte) to do [Hot Module Replacement (HMR)](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#hot). + +## Editor tooling + +The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and there are integrations with various other [editors](https://sveltesociety.dev/tools#editor-support) and tools as well. + +If you're having trouble, get help on [Discord](https://svelte.dev/chat) or [StackOverflow](https://stackoverflow.com/questions/tagged/svelte). diff --git a/site/content/docs/01-getting-started/meta.json b/site/content/docs/01-getting-started/meta.json new file mode 100644 index 000000000000..345e69a3c23a --- /dev/null +++ b/site/content/docs/01-getting-started/meta.json @@ -0,0 +1,3 @@ +{ + "title": "Getting Started" +} diff --git a/site/content/docs/02-component-format.md b/site/content/docs/02-template-syntax/01-dot-svelte-files.md similarity index 63% rename from site/content/docs/02-component-format.md rename to site/content/docs/02-template-syntax/01-dot-svelte-files.md index 90fbc3cd30ed..18c76b3944de 100644 --- a/site/content/docs/02-component-format.md +++ b/site/content/docs/02-template-syntax/01-dot-svelte-files.md @@ -1,14 +1,12 @@ --- -title: Component format ---- - +title: .svelte files --- Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. All three sections β€” script, styles and markup β€” are optional. -```sv +```svelte @@ -20,17 +18,15 @@ All three sections β€” script, styles and markup β€” are optional. ``` -### <script> +## <script> A ` ``` ---- - You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is `undefined`) when instantiating the component. Note that whenever a prop is removed by the consumer, its value is set to `undefined` rather than the initial value. -In development mode (see the [compiler options](/docs/compile-time#svelte-compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`. +In development mode (see the [compiler options](/docs/svelte-compiler#svelte-compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`. -```sv +```svelte ``` ---- - If you export a `const`, `class` or `function`, it is readonly from outside the component. Functions are valid prop values, however, as shown below. -```sv +```svelte ``` -Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/template-syntax#component-directives-bind-this). - ---- +Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/component-directives#bind-this). You can use reserved words as prop names. -```sv +```svelte ``` -#### 2. Assignments are 'reactive' - ---- +### 2. Assignments are 'reactive' To change component state and trigger a re-render, just assign to a locally declared variable. Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect. -```sv +```svelte ``` ---- - Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to trigger the update. This and more details can also be found in the [tutorial](/tutorial/updating-arrays-and-objects). -```sv +```svelte ``` ---- - Svelte's ` ``` -#### 3. `$:` marks a statement as reactive +### 3. `$:` marks a statement as reactive --- Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed. -```sv +```svelte ``` ---- - Only values which directly appear within the `$:` block will become dependencies of the reactive statement. For example, in the code below `total` will only update when `x` changes, but not `y`. -```sv +```svelte Total: {total} - + - + ``` ---- - It is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that `yDependent` will not be updated when `x` is updated in the following example: -```sv +```svelte ``` -#### 4. Prefix stores with `$` to access their values +### 4. Prefix stores with `$` to access their values ---- - -A _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](/docs/run-time#svelte-store) contains minimal store implementations which fulfil this contract. +A _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](/docs/svelte-store) contains minimal store implementations which fulfil this contract. Any time you have a reference to a store, you can access its value inside a component by prefixing it with the `$` character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate. @@ -241,7 +213,7 @@ Note that the store must be declared at the top level of the component β€” not i Local variables (that do not represent store values) must _not_ have a `$` prefix. -```sv +```svelte ``` -##### Store contract +#### Store contract ```js store = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void } ``` -You can create your own stores without relying on [`svelte/store`](/docs/run-time#svelte-store), by implementing the _store contract_: +You can create your own stores without relying on [`svelte/store`](/docs/svelte-store), by implementing the _store contract_: 1. A store must contain a `.subscribe` method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling `.subscribe`. All of a store's active subscription functions must later be synchronously called whenever the store's value changes. 2. The `.subscribe` method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store. @@ -270,9 +242,7 @@ You can create your own stores without relying on [`svelte/store`](/docs/run-tim For interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does. -### <script context="module"> - ---- +## <script context="module"> A ` ``` -### <style> - ---- +## <style> CSS inside a ` ``` ---- - To apply styles to a selector globally, use the `:global(...)` modifier. -```sv +```svelte ``` ---- - If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with `-global-`. The `-global-` part will be removed when compiled, and the keyframe then be referenced using just `my-animation-name` elsewhere in your code. @@ -359,8 +323,6 @@ The `-global-` part will be removed when compiled, and the keyframe then be refe ``` ---- - There should only be 1 top-level ` ``` + +## Tags + +A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag, such as `` or ``, indicates a _component_. + +```svelte + + +
+ +
+``` + +## Attributes and props + +By default, attributes work exactly like their HTML counterparts. + +```svelte +
+ +
+``` + +As in HTML, values may be unquoted. + +```svelte + +``` + +Attribute values can contain JavaScript expressions. + +```svelte +page {p} +``` + +Or they can _be_ JavaScript expressions. + +```svelte + +``` + +Boolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). + +All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`). + +```svelte + +
This div has no title attribute
+``` + +An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed: + +```svelte + +``` + +When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. + +```svelte + + + +``` + +By convention, values passed to components are referred to as _properties_ or _props_ rather than _attributes_, which are a feature of the DOM. + +As with elements, `name={name}` can be replaced with the `{name}` shorthand. + +```svelte + +``` + +_Spread attributes_ allow many attributes or properties to be passed to an element or component at once. + +An element or component can have multiple spread attributes, interspersed with regular ones. + +```svelte + +``` + +_`$$props`_ references all props that are passed to a component, including ones that are not declared with `export`. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases – for example, when you don't know at compile time what props might be passed to a component. + +```svelte + +``` + +_`$$restProps`_ contains only the props which are _not_ declared with `export`. It can be used to pass down other unknown attributes to an element in a component. It shares the same optimisation problems as _`$$props`_, and is likewise not recommended. + +```svelte + +``` + +> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable. + +> Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, ``, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to ``. + +> Another example is ``. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `` to make the image lazily loaded. + +## Text expressions + +```svelte +{expression} +``` + +Text can also contain JavaScript expressions: + +> If you're using a regular expression (`RegExp`) [literal notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor), you'll need to wrap it in parentheses. + +```svelte +

Hello {name}!

+

{a} + {b} = {a + b}.

+ +
{/^[A-Za-z ]+$/.test(value) ? x : y}
+``` + +## Comments + +You can use HTML comments inside components. + +```svelte +

Hello world

+``` + +Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually, these are accessibility warnings; make sure that you're disabling them for a good reason. + +```svelte + + +``` diff --git a/site/content/docs/02-template-syntax/02-logic-blocks.md b/site/content/docs/02-template-syntax/02-logic-blocks.md new file mode 100644 index 000000000000..a5b7b83f615b --- /dev/null +++ b/site/content/docs/02-template-syntax/02-logic-blocks.md @@ -0,0 +1,206 @@ +--- +title: Logic blocks +--- + +## {#if ...} + +```svelte +{#if expression}...{/if} +``` + +```svelte +{#if expression}...{:else if expression}...{/if} +``` + +```svelte +{#if expression}...{:else}...{/if} +``` + +Content that is conditionally rendered can be wrapped in an if block. + +```svelte +{#if answer === 42} +

what was the question?

+{/if} +``` + +Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause. + +```svelte +{#if porridge.temperature > 100} +

too hot!

+{:else if 80 > porridge.temperature} +

too cold!

+{:else} +

just right!

+{/if} +``` + +(Blocks don't have to wrap elements, they can also wrap text within elements!) + +## {#each ...} + +```svelte +{#each expression as name}...{/each} +``` + +```svelte +{#each expression as name, index}...{/each} +``` + +```svelte +{#each expression as name (key)}...{/each} +``` + +```svelte +{#each expression as name, index (key)}...{/each} +``` + +```svelte +{#each expression as name}...{:else}...{/each} +``` + +Iterating over lists of values can be done with an each block. + +```svelte +

Shopping list

+
    + {#each items as item} +
  • {item.name} x {item.qty}
  • + {/each} +
+``` + +You can use each blocks to iterate over any array or array-like value β€” that is, any object with a `length` property. + +An each block can also specify an _index_, equivalent to the second argument in an `array.map(...)` callback: + +```svelte +{#each items as item, i} +
  • {i + 1}: {item.name} x {item.qty}
  • +{/each} +``` + +If a _key_ expression is provided β€” which must uniquely identify each list item β€” Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change. + +```svelte +{#each items as item (item.id)} +
  • {item.name} x {item.qty}
  • +{/each} + + +{#each items as item, i (item.id)} +
  • {i + 1}: {item.name} x {item.qty}
  • +{/each} +``` + +You can freely use destructuring and rest patterns in each blocks. + +```svelte +{#each items as { id, name, qty }, i (id)} +
  • {i + 1}: {name} x {qty}
  • +{/each} + +{#each objects as { id, ...rest }} +
  • {id}
  • +{/each} + +{#each items as [id, ...rest]} +
  • {id}
  • +{/each} +``` + +An each block can also have an `{:else}` clause, which is rendered if the list is empty. + +```svelte +{#each todos as todo} +

    {todo.text}

    +{:else} +

    No tasks today!

    +{/each} +``` + +## {#await ...} + +```svelte +{#await expression}...{:then name}...{:catch name}...{/await} +``` + +```svelte +{#await expression}...{:then name}...{/await} +``` + +```svelte +{#await expression then name}...{/await} +``` + +```svelte +{#await expression catch name}...{/await} +``` + +Await blocks allow you to branch on the three possible states of a Promise β€” pending, fulfilled or rejected. In SSR mode, only the pending state will be rendered on the server. + +```svelte +{#await promise} + +

    waiting for the promise to resolve...

    +{:then value} + +

    The value is {value}

    +{:catch error} + +

    Something went wrong: {error.message}

    +{/await} +``` + +The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible). + +```svelte +{#await promise} + +

    waiting for the promise to resolve...

    +{:then value} + +

    The value is {value}

    +{/await} +``` + +If you don't care about the pending state, you can also omit the initial block. + +```svelte +{#await promise then value} +

    The value is {value}

    +{/await} +``` + +Similarly, if you only want to show the error state, you can omit the `then` block. + +```svelte +{#await promise catch error} +

    The error is {error}

    +{/await} +``` + +## {#key ...} + +```svelte +{#key expression}...{/key} +``` + +Key blocks destroy and recreate their contents when the value of an expression changes. + +This is useful if you want an element to play its transition whenever a value changes. + +```svelte +{#key value} +
    {value}
    +{/key} +``` + +When used around components, this will cause them to be reinstantiated and reinitialised. + +```svelte +{#key value} + +{/key} +``` diff --git a/site/content/docs/02-template-syntax/03-special-tags.md b/site/content/docs/02-template-syntax/03-special-tags.md new file mode 100644 index 000000000000..f70ab4d09276 --- /dev/null +++ b/site/content/docs/02-template-syntax/03-special-tags.md @@ -0,0 +1,84 @@ +--- +title: Special tags +--- + +## {@html ...} + +```svelte +{@html expression} +``` + +In a text expression, characters like `<` and `>` are escaped; however, with HTML expressions, they're not. + +The expression should be valid standalone HTML β€” `{@html "
    "}content{@html "
    "}` will _not_ work, because `
    ` is not valid HTML. It also will _not_ compile Svelte code. + +> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability. + +```svelte +
    +

    {post.title}

    + {@html post.content} +
    +``` + +## {@debug ...} + +```svelte +{@debug} +``` + +```svelte +{@debug var1, var2, ..., varN} +``` + +The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open. + +```svelte + + +{@debug user} + +

    Hello {user.firstname}!

    +``` + +`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions). + +```svelte + +{@debug user} +{@debug user1, user2, user3} + + +{@debug user.firstname} +{@debug myArray[0]} +{@debug !isReady} +{@debug typeof user === 'object'} +``` + +The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when _any_ state changes, as opposed to the specified variables. + +## {@const ...} + +```svelte +{@const assignment} +``` + +The `{@const ...}` tag defines a local constant. + +```svelte + + +{#each boxes as box} + {@const area = box.width * box.height} + {box.width} * {box.height} = {area} +{/each} +``` + +`{@const}` is only allowed as direct child of `{#if}`, `{:else if}`, `{:else}`, `{#each}`, `{:then}`, `{:catch}`, `` or ``. diff --git a/site/content/docs/02-template-syntax/04-element-directives.md b/site/content/docs/02-template-syntax/04-element-directives.md new file mode 100644 index 000000000000..440cc6db920f --- /dev/null +++ b/site/content/docs/02-template-syntax/04-element-directives.md @@ -0,0 +1,763 @@ +--- +title: Element directives +--- + +As well as attributes, elements can have _directives_, which control the element's behaviour in some way. + +## on:_eventname_ + +```svelte +on:eventname={handler} +``` + +```svelte +on:eventname|modifiers={handler} +``` + +Use the `on:` directive to listen to DOM events. + +```svelte + + + +``` + +Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters. + +```svelte + +``` + +Add _modifiers_ to DOM events with the `|` character. + +```svelte +
    + +
    +``` + +The following modifiers are available: + +- `preventDefault` β€” calls `event.preventDefault()` before running the handler +- `stopPropagation` β€” calls `event.stopPropagation()`, preventing the event reaching the next element +- `stopImmediatePropagation` - calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired. +- `passive` β€” improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) +- `nonpassive` β€” explicitly set `passive: false` +- `capture` β€” fires the handler during the _capture_ phase instead of the _bubbling_ phase +- `once` β€” remove the handler after the first time it runs +- `self` β€” only trigger handler if `event.target` is the element itself +- `trusted` β€” only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action. + +Modifiers can be chained together, e.g. `on:click|once|capture={...}`. + +If the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it. + +```svelte + +``` + +It's possible to have multiple event listeners for the same event: + +```svelte + + + +``` + +## bind:_property_ + +```svelte +bind:property={variable} +``` + +Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent. Most bindings are specific to particular elements. + +The simplest bindings reflect the value of a property, such as `input.value`. + +```svelte + + - - -``` - ---- - -If the name matches the value, you can use shorthand. - -```sv - - - -``` - ---- - -Numeric input values are coerced; even though `input.value` is a string as far as the DOM is concerned, Svelte will treat it as a number. If the input is empty or invalid (in the case of `type="number"`), the value is `undefined`. - -```sv - - -``` - ---- - -On `` elements with `type="file"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). It is readonly. - -```sv - - -``` - ---- - -If you're using `bind:` directives together with `on:` directives, the order that they're defined in affects the value of the bound variable when the event handler is called. - -```sv - - - -``` - -Here we were binding to the value of a text input, which uses the `input` event. Bindings on other elements may use different events such as `change`. - -##### Binding `` value binding corresponds to the `value` property on the selected ` - - - - -``` - ---- - -When the value of an `