Express将原始html呈现为文本

时间:2017-05-02 13:14:22

标签: javascript html express

我尝试将html表格渲染到/guestbook.ejs,然后将guestbook.ejs重定向到/ guestbook。但是,我的guestbook.ejs将html代码显示为纯文本。

这是我的代码:

server.js:

app.get('/guestbook', function(req, res) {
    var data = require('./guestbook.json');

    var table =
     '<table border="1"> ';
    for (var i=0; i < data.length; i++){
        table +=
        '<tr>' +
        '<td>' + data[i].id + '</td>' +
        '<td>' + data[i].username + '</td>' +
        '<td>' + data[i].country + '</td>' +
        '<td>' + data[i].date + '</td>' +
        '<td>' + data[i].message + '</td>' +
        '</tr>';
    }
    res.render('pages/guestbook.ejs', {
        new_table: table
    });

    res.sendfile('/views/pages/guestbook.ejs');
});

guestbook.ejs:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>


 <div><%= new_table %></div>


</body>
</html>

,结果字面意思是文本格式:

<table border="1"> <tr><td>1</td><td>Pam</td><td>Anguilla</td><td>Thu Feb 22 2007 22:28:32 GMT+0200 (FLE Standard Time)</td><td>How are you guys doing?</td></tr><tr><td>2</td><td>Sofia</td><td>Macau</td><td>Mon Apr 05 1993 09:12:01 GMT+0300 (FLE Daylight Time)</td><td>Hello world!</td></tr><tr><td>3</td><td>Ashley</td><td>Mauritania</td><td>Sat Oct 19 1991 01:31:38 GMT+0300 (FLE Daylight Time)</td><td>Greetings from Mauritania!</td></tr><tr><td>4</td><td>Baxter</td><td>Malta</td><td>Sat Sep 03 2005 08:52:38 GMT+0300 (FLE Daylight Time)</td><td>Very nice!</td></tr><tr><td>5</td><td>Vickie</td><td>Uganda</td><td>Tue Jul 22 2003 08:53:21 GMT+0300 (FLE Daylight Time)</td><td>Anyone from Africa here?</td></tr><tr><td>6</td><td>testid</td><td>test</td><td>2017-04-29T09:05:01.408Z</td><td>21</td></tr><tr><td>7</td><td>testd</td><td>2</td><td>2017-04-29T09:05:08.669Z</td><td>123</td></tr><tr><td>8</td><td>test</td><td>123</td><td>2017-04-30T12:43:54.848Z</td><td>231</td></tr>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

将文字呈现为HTML:使用<%- new_table %>