簡體   English   中英

在ejs include上添加變量

[英]add variable on ejs include

我正在嘗試根據博客的name使用來自ejs的include來加載博客部分。

來自data.json的數據:

"blogs" : [{
    "title" : "Git Basics",
    "name" : "git_basics",
    "date" : "February 8, 2015",
    "category" : "git",
  },{
    "title" : "Javascript Basics",
    "name" : "javascript_basics",
    "date" : "December 31, 2014",
    "category" : "javascript"
  },{
    "title" : "Html5 Communication",
    "name" : "html5_communication",
    "date" : "November 25, 2014",
    "category" : "html5"
  }]    

路線:

/* GET blog page. */
router.get('/blog', function(req, res) {
  var blogswithDetail = [];
  for(var i=0; i<appdata.blogs.length && i<4; i++){
    blogswithDetail.push(appdata.blogs[i]);
  }

  res.render('blog', { 
    title: 'Blog',
    blogswithdetail: blogswithDetail
  });
});

頁:

<% blogswithdetail.forEach(function(item){ %>
    <article id="<%= item.name %>">
        <h2><%= item.title %></h2>
        <p><%= item.date %></p>
        <%= item.detail %>
    </article>
    <% include partials/content/blog_(item.name).ejs %>
<% }); %>

<% include partials/content/blog_(item.name).ejs %>這行代碼不正確。 我的問題是如何將item.name插入include ,所以我可以根據item.name的變化包括不同的部分

我認為您誤解了ejs的工作原理。 ejs接受提供的參數,並用參數替換標記:

node.js:

res.render('test.ejs', {a: 'hello', b: 'world', c: 42});

test.ejs:

<%= a %><%= b %><br>
The answer to life, universe and everything else is <%= c %>

結果:

helloworld<br>
The answer to life, universe and everything else is 42

您可以傳遞對象:

res.render('test.ejs', {a: {a: 'a', b: 'b'}});

但是您不能使用對象的屬性,而只能使用整個對象。

對於您的情況,您應該執行以下操作:

節點:

var item = {name: 'name', title: 'title', date: 'date', details: 'details'};
res.render('test.ejs', item);
//Or
//res.render('test.ejs', {name: item.name, title: item.title...

ejs:

<% blogswithdetail.forEach(function(item){ %>
    <article id="<%= name %>">
        <h2><%= title %></h2>
        <p><%= date %></p>
        <%= detail %>
    </article>
    <% include partials/content/blog_(<%= name %>).ejs %>
<% }); %>

要么:

<% blogswithdetail.forEach(function(){ %>
    var item = JSON.parse(<%= item %>);
    <article id="item.name">
        <h2>item.title</h2>
        <p>item.date</p>
        item.detail
    </article>
    <% include partials/content/blog_(item.name).ejs %>
<% }); %>

節點:

res.render('test.ejs', {item: JSON.stringify(item)});

我認為您在這里錯過了竅門。 開發任何Web應用程序時,都應嘗試使其動態化。 過去擁有數百個HTML並根據路由加載它們的日子已經一去不復返了,這基本上被稱為靜態網絡。

我從您的問題中了解到的是,您正在嘗試根據參數值加載特定的EJS模板。 試想一下一種情況,隨着時間的推移,您的項目會越來越大,因此您的參數值以及每個特定的參數都將創建一個新的EJS模板,該模板與其他模板沒有太大不同。 將有100多個文件將很難管理。

因此,我建議您使用正確的模板方法。 只需在其中包含一個EJS模板,並在其中使用表達式即可區分您的item.name並根據需要渲染視圖。 當然,您必須明智地使用它,如果您認為有可能簡化使用,應將模板破壞得更小,然后重新使用現有模板。

例如:

<%if (item.name == 'xyz') { %>
// Do something 
<% } %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM