【问题标题】:How to add variable inside of .EJS template如何在 .EJS 模板中添加变量
【发布时间】:2019-08-08 09:30:24
【问题描述】:

我有一个索引页面、一个关于页面和一个联系页面。我也有一个 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>

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

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

    【讨论】:

    • 尝试传递变量时出错。我会玩它,看看如何正确传递页面。非常感谢!我真的很感激帮助
    【解决方案2】:

    使用include函数时,必须省略.ejs

    例如,在您的 index.ejs 上:

    <%- include 'templates/header' %>
    

    如果您想重复使用相同的模板,您应该将您可能决定呈现的所有“可选”内容放在单独的 .ejs 文件中,然后只要满足条件,您就可以执行以下操作:

    somePage.ejs:

    <p>Welcome to <%= title %></p>
    

    someOtherPage.ejs:

    <p>Goodbye <%= title %></p>
    

    index.ejs:

    <%- include 'templates/header' %>
    
    <% if (someVar == true) { %>
    <%- include 'somePage' %>
    <% } %>
    
    <% else if (someOtherVar == true) { %>
    <%- include 'someOtherPage' %> 
    <% } %>
    

    最后,在你的app.js

    app.get('somePath', function(req, res) {
      res.render('index', {someVar:true, someOtherVar:false}); //pass variables to template like this
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2020-05-12
      • 1970-01-01
      • 2014-10-25
      • 2016-03-06
      相关资源
      最近更新 更多