如何在Node.js和Express中以嵌套形式呈现多个.ejs文件?

Bla*_*ard 7 rendering ejs node.js express

如何.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})
            });
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

其中index.ejs包含非常基本的html标签(比如html,head,body和one ptag),并且<%- content %>其中包含其他.ejs文件,其中不包含html,head或body标签的内容.仅假定呈现内容和标题.但是,当我通过POST请求访问此文件并尝试呈现文件然后从我的浏览器检出输出的HTML文件时,内容仅包含index2.ejs文件,这意味着它没有html,body,head标签.

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

ver*_*loc 13

首先,我认为你对如何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 %>
Run Code Online (Sandbox Code Playgroud)

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

res.render('index', {
                 title: 'title', 
                 content: 'index2', 
                 data:rows
            });
Run Code Online (Sandbox Code Playgroud)

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

<html><head>
<title><%= title %></title></head>
<body><p>
<%- partial('index2',{}) %>
</p></body></html>
Run Code Online (Sandbox Code Playgroud)

此方法的优点是您可以使用额外对象将额外值传递给视图.查看ejs-locals github页面了解更多详情.