首页 > 解决方案 > 如何在 .EJS 模板中添加变量

问题描述

我有一个索引页面、一个关于页面和一个联系页面。我也有一个 header.ejs 文件。在 header.ejs 里面我有这个:

<a href="/">Home</a> |
<a href="/about">My Resume</a> |
<a href="contact">My Contact Info</a>
<br>
_______________________________________

-----------------------------------------
<br>


<h3>Copyright 2019  Some text here</h3>

我想为关于和联系页面的索引使用完全相同的头文件。我希望每个页面的内容有所不同。此内容将放置在实线和虚线内。我不能使用单独的头文件。我只能用一个。如何使用相同的模板,但创建空间并为每个页面填充不同的内容?这是我的索引文件的示例:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <%include templates/header.ejs%>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

标签: javascriptnode.jsexpressejs

解决方案


page在头文件中添加变量:

<a href="/">Home</a> |
<a href="/about">My Resume</a> |
<a href="contact">My Contact Info</a>
<% if(page=='home') { %>
  // add your home page header content here 
<% }else if(page=='contact'){%>
 // add your contact page header content here 
<% }else if(page=='resume'){%>
 // add your resume page header content here 
<% }else{ %>
  // default header
<% } %>
<h3>Copyright 2019  Some text here</h3>

通过传递页面变量来包含它:

主页:

<%- include('templates/header', {page: 'home'}); %>

联系页面:

<%- include('templates/header', {page: 'contact'}); %>

推荐阅读