📅  最后修改于: 2023-12-03 15:14:51.108000             🧑  作者: Mango
EJS (Embedded JavaScript) is a simple and powerful templating engine that allows embedded JavaScript code to generate HTML markup. In this article, we will explore how to use the if-else statement in EJS.
The if-else statement is used to control the flow of the EJS template. The syntax for if-else in EJS is similar to that of JavaScript.
<% if (condition) { %>
<!-- code to execute if condition is true -->
<% } else { %>
<!-- code to execute if condition is false -->
<% } %>
In the above syntax, the condition is defined inside the if statement. If the condition evaluates to true, the code inside the first block will be executed. If the condition evaluates to false, the code inside the else block will be executed.
Let's consider a simple example of using if-else in EJS. Suppose we want to display different messages depending on whether the user is logged in or not. We can use the following code:
<% if (loggedIn) { %>
<h1>Welcome <%= userName %>!</h1>
<% } else { %>
<h1>Please log in to continue.</h1>
<% } %>
In the above example, we have defined a condition based on the loggedIn
variable. If the variable is true, the message "Welcome" followed by the userName
variable will be displayed. If the variable is false, the message "Please log in to continue" will be displayed.
The if-else statement is a powerful tool for controlling the flow of EJS templates. It allows us to generate dynamic content based on specific conditions. By using if-else in EJS, we can create highly customized and interactive HTML pages that respond to user input and behavior.