Check out a free preview of the full Svelte course:
The "if else Blocks" Lesson is part of the full, Svelte course featured in this preview video. Here's what you'd learn in this lesson:

Rich demonstrates ways of using logic, like conditionals if else statements and loops in Svetle templates.

Get Unlimited Access Now

Transcript from the "if else Blocks" Lesson

>> In just about every web application, you will need to use logic inside your template. Whether that's if blocks to control whether or not something is rendered or each blocks, which control how lists of things are rendered. And HTML doesn't have a native way of declaring conditions. So we've added some syntax inside Svelte that lets you do that.

[00:00:25] So here we've got two buttons, one is a login button and one is a logout button. And we only wanna show one at a time because they're obviously mutually exclusive. And we can do that by wrapping the buttons in an if block that looks like this. If user.loggedIn, indent that, and then close the if block like so.

[00:00:50] And then we're gonna add the same thing for the second one, except with this time, we're inverting the condition. And so now only one of the buttons is shown at any one time. If I click on this, then it's no longer rendered, and it gets replaced with the opposite button.

[00:01:15] Now this is a common case, the two conditions, user.loggedIn and user not logged in are mutually exclusive. So we can replace the two if blocks with a single if-else block, just like you would in JavaScript. And that looks like this, :else here. And that behaves exactly the same way.

[00:01:37] So there are three new bits of syntax here. When we're opening a block, we use the pound sign. When we're continuing a block, we use the colon sign. And when we're closing it, we use the slash, just like when you're closing an element. And that's something that you'll see in other types of blocks that we'll introduce soon.

[00:01:55] And that's basically the entirety of the Svelte syntax that you need to learn, apart from element directors, which we'll come to soon. We can also have else-if blocks. So here we've got an if block and then we've got an else block, and then inside the else block we've got another if-else block.

[00:02:18] It'd be easier if we could have an else if 5 is greater than x. So x = 7. If it's greater than 10, render this, otherwise, if it's greater than, or if it's less than x, Then show that, and then we can get rid of the closing if block.

[00:02:42] Reindent everything, and that behaves exactly as it would in JavaScript.