首页 > 解决方案 > 模板引擎将我的代码设置到错误的位置。有什么错误?

问题描述

模板引擎将我的代码设置到表格标题的错误位置。它成功地设置了简单的字符串对象,但它设置了我的表格行绝对错误。

应用程序.js

app.get("/", function(req,res) {

    const collection = req.app.locals.collection;
    collection.find({}).toArray(function(err, messages) {

        participants = Analise(messages, collection);
        console.log(participants);

        if(err) return console.log(colors.red(err));

        res.render("main.hbs", {
            title: "tg:analitycs",
            captition: "Таблица пользователей",
            cap: "",
            table: genTable(participants),
        });
    });
});

function genTable(p) {
    let rows = '';
    for (let i=0; i<p.length; i++) {

        rows += "<tr><th>"+p[i].id+"</th><th>"+p[i].first_name+"</th><th>"+p[i].last_name+"</th><th>"+p[i].username+"</th><th>"+p[i].total+"</th><th>"+p[i].type_text+"</th><th>"+p[i].type_image+"</th></tr>";
    }
    return rows;
}

主文件

<body>
    {{> header}}
    <div class="container">
        <div class="test_container">
            <ul>
                <li>{{captition}}</li>
                <li>{{cap}}</li>
            </ul>
            <table>
                <tr>
                    <th>user_id</th>
                    <th>First name</th>
                    <th>Last name</th>
                    <th>Username</th>
                    <th>total messages</th>
                    <th>text</th>
                    <th>images</th>
                </tr>
                {{table}} <!---------- MUST BE HERE ----------->
            </table>
        </div>
    </div>
    {{> footer}}
</body>

通过链接输出截图:https ://jonarhipov.neocities.org/screenshots/Screenshot%202019-06-26%20at%2015.57.57.png

哪里是错误,或者它是一个错误?谢谢!

PS:渲染表格的最佳方式是什么?我想:

我不想添加行、删除行、更改行。仅输出表。

标签: node.jsexpresstemplate-engine

解决方案


首先,将变量中的所有集合数据发送到 html 页面,如:

    res.render("main.hbs", {
        title: "tg:analitycs",
        captition: "Таблица пользователей",
        cap: "",
        user_data: participants
    }); 

那么表格应该是这样的:

 <table>
    <thead>
        <tr>
            <th>user_id</th>
            <th>First name</th>
            <th>Last name</th>
            <th>Username</th>
            <th>total messages</th>
            <th>text</th>
            <th>images</th>
        </tr>
    </thead>

    <tbody>
        <tr>
        {% for data in user_data %}
            <td>{{data.id}}</td>
            <td>{{data.first_name}}</td>
            ...
            ...

        </tr>
        {% endfor %}
    </tbody>
 </table>

推荐阅读