In EJS (Embedded JavaScript templating), including templates with parameters is a highly valuable feature that enables code reuse and maintains your project's organization and clarity. Below, I will provide a detailed explanation of how to implement this functionality, along with a concrete example.
Step 1: Create the Main Template and Included Template
First, you need two template files: one is the main template, and the other is the template you intend to include. Let's assume we have a main template main.ejs and an included template user.ejs.
Step 2: Define Parameters in the Included Template
In user.ejs, you can define parameters that will be passed to it. For instance, this template might display user information, with parameters such as username and age.
user.ejs
html<p>用户名: <%= username %></p> <p>年龄: <%= age %></p>
Step 3: Include and Pass Parameters in the Main Template
In the main template main.ejs, you can use the <%- include('user', {username: '张三', age: 28}) %> syntax to include the user.ejs template while passing the required parameters.
main.ejs
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Information</title> </head> <body> <h1>Welcome to View User Information</h1> <%- include('user', {username: '张三', age: 28}) %> </body> </html>
Example
Assume we run the above EJS templates; the final output displayed in the browser will be:
shellWelcome to View User Information 用户名: 张三 年龄: 28
Summary
By implementing this approach, you can flexibly include other templates in EJS while passing any necessary parameters. This technique is particularly useful for scenarios requiring repeated reuse of layouts or components, such as user information cards or navigation bars. It not only enhances code reusability but also improves project structure clarity and maintainability.