📜  ejs 中的组件 - Html (1)

📅  最后修改于: 2023-12-03 15:30:36.302000             🧑  作者: Mango

EJS 中的组件: HTML

在 EJS 中,HTML 组件是一种可重用的代码块,可以在多个页面中使用。它们可以包含 HTML、CSS 和 JavaScript 代码,从而简化和加速页面开发。

创建 HTML 组件

要创建 HTML 组件,首先需要创建一个包含组件代码的文件,例如 header.ejs,然后在主页面中使用 <%- include('header') %> 来引用它。

header.ejs
<header>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About Us</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
</header>
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <%- include('header') %>

    <main>
        <h1>Welcome to My Website</h1>
        <p>This is the homepage of my website. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </main>
</body>
</html>
传递数据到 HTML 组件

可以通过传递数据对象来向 HTML 组件传递数据,例如:

header.ejs
<header>
    <h1><%= title %></h1>
    <nav>
        <ul>
            <% for(var i=0; i<navLinks.length; i++) { %>
                <li><a href="<%= navLinks[i].url %>"><%= navLinks[i].label %></a></li>
            <% } %>
        </ul>
    </nav>
</header>
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <%- include('header', { title: 'My Website', navLinks: [{ url: '#', label: 'Home' }, { url: '#about', label: 'About Us' }, { url: '#contact', label: 'Contact' }] }) %>

    <main>
        <h1>Welcome to My Website</h1>
        <p>This is the homepage of my website. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </main>
</body>
</html>
总结

使用 HTML 组件可以帮助程序员更有效地开发页面。它们次构性高,可重用,可以传递数据。