在ejs中的function

我想要的是这样的:

app.js (节点进程,包括排除为简洁,但使用ejs作为渲染引擎):

app.get('/', function(req, res){ var ejsVariables = { title : 'ideal ejs function example', listData1 : { listTitle : 'my list', listItems : [ { name : 'first item', class : 'foo' }, { name : 'second item', class : 'bar' }, { name : 'last item', class : 'foo' } ] }, listData2 : { listTitle : 'your list', listItems : [ { name : 'a widget', class : 'foo' }, { name : 'another widget', class : 'baz' } ] } }; res.render('index', ejsVariables); }); 

index.ejs

 <html> <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <% makeList(listData1) %> <p>lorem ipsum</p> <% makeList(listData1) %> </body> </html> 

???


结果

 <html> <head> <title>ideal ejs function example</title> </head> <body> <h1>ideal ejs function example</h1> <ul> <li class="foo">first item</li> <li class="bar">second item</li> <li class="foo">another item</li> </ul> <p>lorem ipsum</p> <ul> <li class="foo">a widget</li> <li class="baz">another widget</li> </ul> </body> </html> 

问题是什么? 部分和/或应改变以上?


到目前为止,我已经尝试过

尝试1

– 我真的想要这个工作,它不是

index.ejs

 <html> <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <% var makeList; %> <!-- this variable is declared here as those declared within the include are not accessible from the file from which it is called, I'm guessing some sort of function scope is coming into play here --> <% include makeList %> <% makeList(listData1) %> <p>lorem ipsum</p> <% makeList(ListData2) %> </body> </html> 

makeList.ejs

 <% function makeListItem(itemData){ %> <li class="<%= itemData.class %>" ><%= itemData.name %></li> <% } %> <% makeList = function(data){ %> <% if(data){ %> <ul> <% data.map(makeListItem) %> </ul> <% } %> <% } %> 

在这种情况下, makeListItemmakeList都被调用,只是由于作用域或其他原因,当它们被调用时,它们无法实际输出到模板。


尝试2

– 这实际上工作,我只是不喜欢我最终使用包括而不是某种函数调用。

index.ejs

 <html> <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <% var data = listData1 %> <% include makeList %> <p>lorem ipsum</p> <% var data = listData2 %> <% include makeList %> </body> </html> 

makeList.ejs

 <% function makeListItem(itemData){ %> <li class="<%= itemData.class %>" ><%= itemData.name %></li> <% } %> <% if(data){ %> <ul> <% data.map(makeListItem) %> </ul> <% } %> 

尝试3

– 这基本上涉及与ejs当地人混乱,但是我发现function有点缺乏。

如果我要在我的应用程序中包含另一个npm模块,我真的希望它是一个更完整的解决scheme,但即使在理想的世界中,我宁愿不去做,并自己写。


对这篇文章的长度抱歉,它很快就失控了。 如果你有这么多,我赞扬你。

任何投入将不胜感激。

这个怎么样:

 // app.js var ejs = require('ejs'); var fs = require('fs'); app.locals({ makeList : function(list) { var template = fs.readFileSync('makeList.ejs', 'utf-8'); return ejs.render(template, list); } }); // index.ejs <%- makeList(listData1) %> ^ important! // makeList.ejs <ul> <% listItems.forEach(function(item) { %> <li class="<%= item.class %>"><%= item.name %></li> <% }); %> </ul> 

我能想到的唯一的东西(至less在第一个例子中)是从ejsVariables中删除listData1的makeList()函数,你能告诉我这个例子的makeList()吗?

在尝试1中,您正在调用没有参数的makeList()!