7

如何.ejs以嵌套形式呈现多个文件?

所以我有以下文件:

var mysql = require('mysql');
var ejs = require('ejs');
exports.index = function(req, res){
    if (req.method=='POST'){
        var connection = mysql.createConnection({user:'root', password:'root', database:'testdb'});
        var name = req.param('name');
        connection.query('select * from table_name where name = ?', name, function(err, rows, fields){
            if(err) throw err;
            res.render('index', {
                 title: 'title', content: res.render('index2', {data:rows})
            });
        });
    }
});

whereindex.ejs由非常基本的 html 标记(比如 html、head、body 和一个p标记)组成并包含<%- content %>在其中,其中内容假定由另一个 .ejs 文件呈现,该文件不包括 html、head 或 body 标记和仅假定呈现内容和标题。但是,当我通过 POST 请求访问该文件并尝试渲染文件然后从浏览器中检出输出的 HTML 文件时,内容仅由index2.ejs文件组成,这意味着它没有 html、body、head 标记。

那么我错过了什么?如果我想包含一个 Javascript 库<script src='some_file.js'></script>,我应该在尝试在index2.ejs文件中渲染时添加另一个渲染属性......对吗?

4

2 回答 2

14

首先,我认为您对如何res.render操作感到困惑。根据文档

res.render(视图,[本地],回调)

渲染一个带有回调的视图,该回调响应渲染的字符串。

这解释了为什么您只在 HTML 页面中看到 index2.ejs 的内容。


现在,有多种方法可以实现您的目标,即在视图中嵌套视图。从 Express 3.x 开始,您需要使用include. 在这种情况下,您可以像这样重写您的视图:
1- 定义一个 header.ejs 文件,它看起来像这个示例
2-定义一个footer.ejs。这看起来像另一个例子
3- 在您的 index2.ejs 中,包括这两个文件,如下所示:

<% include header %>
    //The HTML of your index2.ejs
    //You can add some reusable views, like, say, a submit button above the footer
    <% include reusable_views/submit %>
<% include footer %>

第二种方法是使用ejs-locals,它允许您通过仅指定路径来插入任何视图:

res.render('index', {
                 title: 'title', 
                 content: 'index2', 
                 data:rows
            });

而且,在您的 index1.ejs 中,您将拥有:

<html><head>
<title><%= title %></title></head>
<body><p>
<%- partial('index2',{}) %>
</p></body></html>

这种方法的优点是您可以使用额外的对象将额外的值传递给您的视图。查看 ejs-locals github 页面了解更多详细信息。

于 2013-06-10T08:06:27.360 回答
3

更新:用于布局的 ejs-mate Express 4.x 局部变量。

https://www.npmjs.com/package/ejs-mate

cf https://scotch.io/tutorials/use-ejs-to-template-your-node-application

于 2015-04-28T11:18:32.130 回答