The #if block is the simplest form of control flow in Svelte. It allows you to conditionally render content based on a boolean expression. If the expression evaluates to true, the content inside the #if block is displayed; otherwise, it’s hidden.
Here’s a basic example:
In this example, the isVisible state variable controls whether the paragraph is displayed. Clicking the button toggles the value of isVisible, showing or hiding the message.
This is a simple yet powerful way to control what your users see based on the state of your application.
While #if is great for simple conditions, you’ll often need to handle multiple conditions. This is where #else-if and #else come in. The #else-if block allows you to check additional conditions if the previous #if or #else-if block evaluates to false. The #else block provides a fallback for when none of the conditions are met.
Let’s look at an example where we display different messages based on a user’s role:
In this example, the message displayed depends on the value of userRole. If userRole is null, the #else block ensures a default message is shown. This structure makes it easy to handle complex logic while keeping your code clean and readable.
