Notes: Svelte - Special Tags
Another page containing notes about Svelte. As before, I’ll keep the structure the same. Quotes will be quoted via >
and explanation will follow. Notes are separated using ---
horizontal lines
Notes
{@html expression}
In a text expression, characters like
<
and>
are escaped; however, with HTML expressions, they’re not.
This is a pretty useful concept. If you wanted dynamic HTML to load from a server or something, you’d want to load it into a thing like this.
Not sure how it would work with CSS styling, specifically whether the html in this tag would receive the styling defined in the component. My intuition is it would be styled.
The expression should be valid standalone HTML —
{@html "<div>"}content{@html "</div>"}
will not work, because</div>
is not valid HTML. It also will not compile Svelte code.
A good thing to keep in mind, though it’s a bit hard to imagine why someone would want to do this.
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.
Important security risk to consider when loading user-defined html into one of these blocks.
{@debug var1, var2, ..., varN}
The
{@debug ...}
tag offers an alternative toconsole.log(...)
. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open.
Ah, this is super useful. Especially in the context of variables changing due to reactive updates. Probably 80% of debugging could be accomplished by looking at state/variable changes with this tag.
{@debug ...}
accepts a comma-separated list of variable names (not arbitrary expressions).<!-- Compiles --> {@debug user} {@debug user1, user2, user3} <!-- WON'T compile --> {@debug user.firstname} {@debug myArray[0]} {@debug !isReady} {@debug typeof user === 'object'}
Good thing to keep in mind about the limits of the {@debug}
tag. Would be nice if it supported arbitrary expressions, though.
The
{@debug}
tag without any arguments will insert adebugger
statement that gets triggered when any state changes, as opposed to the specified variables.
Interesting. I don’t think I’ve used the browser debugger explicitly yet (all just console.log
so far). This could be worth giving a shot, though.
The
{@const ...}
tag defines a local constant.
<script> export let boxes; </script> {#each boxes as box} <!-- a helpful constant --> {@const area = box.width * box.height} {box.width} * {box.height} = {area} {/each}
I guess this could be useful, but seems pretty niche. I generally avoid things like this (defining variables in my markup), as it seems to lead to complexity/logic in a part of my app that I want to be stateless (or rather, a pure function of state). But not a bad thing to have in the toolkit.