gpt4 book ai didi

javascript - 遍历数组时处理数学表达式

转载 作者:行者123 更新时间:2023-11-30 15:37:46 24 4
gpt4 key购买 nike

我在练习node,遇到了一个小问题。我使用 handlebars 作为模板引擎,使用 mongoose 与我的数据库进行交互。在我的 .hbs 模板中,我循环遍历数据库中的每条记录,当然我将这些记录传递到我的 View 中

router.get('/', function(req, res, next) {
Exam.find(function(err, predmeti) {
if (err) {
console.log(err);
}
res.render('index',{
predmeti: predmeti
})
})

});

现在,当我使用 #each 循环遍历 predmeti 时,当我尝试执行诸如

之类的数学表达式时,引擎会抛出错误
{{#each predmeti}}
<h1>{{100/(brKolokvijuma/finished)}}</h1>
{{/each}}

brKolokvijuma 和 finished 都有一个数字值,但出于某种原因我得到一个错误 Expecting ID got OPEN_SEXPR

所以我假设当我循环遍历一个数组时,handlebars 不会让我做数学表达式。我该如何解决这个问题?

最佳答案

Handlebars 有一些插件可以让你做他们认为你不应该在 View 中做的事情,但每个人仍然想做。

例如the Assemble.io maths helpers嵌套表达式将使您能够执行以下操作:

{{#each predmeti}}
<h1>{{divide 100 (divide brKolokvijuma finished)}}</h1>
{{/each}}

第二种方法,如果您的数学表达式没有那么多变并且围绕您的观点重复使用(常见计算,例如税收或舍入),您可以编写自己的更简单/更轻的插件:

Handlebars.registerHelper("divideMyThings", function(thing1, thing2, thing3) {
return thing1 / thing2 / thing3;
});

在您的模板中调用:

{{divideMyThings 100 brKolokvijuma finished}}

第三,您通常可以预先计算数据表,直到只有一个变量,然后使用 builtin lookup feature .这不需要额外的插件。这可能对这个特定问题没有帮助,但我想我会把它作为一种工具来提及。

关于javascript - 遍历数组时处理数学表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41262138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com