如何使用车把助手打印 JSON 个对象

How to printing JSON objects using handlebar helpers

我想在我的 html 模板(车把)上打印一个对象。该值是来自 mysql 服务器的计数查询。这是其中包含查询的函数:

function getGrade7Applicants(req, res, next) {
connection.query('SELECT COUNT(*) FROM applications WHERE grade="Grade 7" ', function (err, rows, fields) {
    if (err) {
        return next(err);
    };
    req._applications7 = rows;
    return next();
});
}

这是我对路由器文件的 GET 请求:

router.get('/dashboard', getGrade7Applicants, function (req, res, next) {
res.render('admission/dashboard', {
    applications: {
            'grade7': req._applications7
    }

});
});

车把配置如下:

Handlebars.registerHelper('toJSON', function(object){
return new Handlebars.SafeString(JSON.stringify(object));
});

最后我的 html 模板是:

<div class="alert alert-success" role="alert">
            <p style="font-size:75px; text-align:center;">{{toJSON applications.grade7}}</p>               
            <p style="text-align:center;"><strong>7th GRADE Applications<strong> </p>
        </div>

所有这些之后,我网页上的输出是 [{"COUNT(*)":20}]

我真的不知道为什么它会打印部分查询。 20 是我想要打印的正确值。

那不是查询的一部分..那是字段的名称 - 因为您没有指定字段名称,它只使用 "count(*)"。

您需要更改您的查询以包含您可以使用的名称,如下所示:

 Select count(*) as app_count from applications...

然后就可以通过applications.gradet.app_count获取值打印出来了。

我不是 100% 确定你试图通过字符串化一个对象来实现什么,因为你必须 re-parse 它才能得到你的对象 属性 的值。

我对车把不太熟悉,所以我可能会误导您。

上面说的就是属性这个名字,这里再做一些解释:

如果您有以下查询(我给计数取了一个结果名称,使显示更多 display-friendly:

SELECT COUNT(*) as result FROM applications WHERE grade="Grade 7"

你应该得到一个看起来像这样的结果对象:

[{
   "result": "20"
}]

因此,当您对其进行字符串化时,您会得到整个对象,包括道具名称和括号作为文本。

您可以传入整个数组并在模板中遍历它(您拥有的),或者只是第一个元素,然后在模板中按名称访问 属性:

res.render('admission/dashboard', {
    applications: {
        'grade7': req._applications7[0]
    }
});

并在模板中:

{{#if applications}}
    {{#if applications.grade7}}
        {{applications.grade7.result}}
    {{/if}}
{{/if}}

您也可以直接在数据中传递值:

res.render('admission/dashboard', {
    applications: {
        'grade7': req._applications7[0].result //prop name specified
    }
});

在您的模板中:

{{#if applications}}
    {{#if applications.grade7}}
        {{applications.grade7}}
    {{/if}}
{{/if}}

除非有非常具体的原因,否则您不需要使用帮助程序。