javascript - 如何在 .EJS 模板内添加变量

标签 javascript node.js express 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>

最佳答案

在头文件中添加变量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'}); %>

关于javascript - 如何在 .EJS 模板内添加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214160/

相关文章:

javascript - 比较Mongoose Doc和Express当前日期中的日期

javascript - JavaScript 函数无法引用动态图像 ID

javascript - ChartJS : Draw vertical line at data point on chart on mouseover

javascript RegExp 不过滤数字

javascript - 找不到模块 : Error: Can't resolve './home.html' in '/Users/username/Documents/Privat/ionic3-barcodev3/src/app/home'

node.js - Mongoose getter 和 setter 无法正常工作

json - NodeJS Photoshop PSD 解析器 toJSON() 没有方法

node.js - 预保存和验证之间的 Mongoose 区别?什么时候用哪一个?

javascript - Node.js、puppeteer 和延迟加载

javascript - 关于expressjs中next()函数的问题