express中的app.locals的问题 - CNode技术社区

express中的app.locals的问题
发布于 9 年前 作者 mengLLLL 4626 次浏览 来自 问答

需求是这样的,将得到的数字(秒)转成...分...秒,我写了一个formatSeconds函数,想在jade模版中使用 函数

function formatSeconds(value) {
 var theTime = parseInt(value);// 秒 
 var theTime1 = 0;// 分 
 var theTime2 = 0;// 小时 
 // alert(theTime); 
 if (theTime > 60) {
 theTime1 = parseInt(theTime / 60);
 theTime = parseInt(theTime % 60);
 // alert(theTime1+"-"+theTime); 
 if (theTime1 > 60) {
 theTime2 = parseInt(theTime1 / 60);
 theTime1 = parseInt(theTime1 % 60);
 }
 }
 var result = "" + parseInt(theTime) + "秒";
 if (theTime1 > 0) {
 result = "" + parseInt(theTime1) + "分" + result;
 }
 if (theTime2 > 0) {
 result = "" + parseInt(theTime2) + "小时" + result;
 }
 return result;
}
module.exports = formatSeconds

express的app文件

app.locals.formatSeconds = require("/static/js/lib/formatSeconds.js")

jade中的使用

#{formatSeconds(totalTime)}

问题:报错:formatSeconds is not a function

请问是我的用法错了吗还是怎样,求解

3 回复
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
 res.render('index', {
 title: 'Express',
 formatSeconds: app.locals.formatSeconds
 });
});
module.exports = router;

要么传参,要么就写在jade模板里。

是不是app.locals设置的位置不对?一定要在路由之前设置。 在你设置app.locals的地方log 一下它, 看看是什么

回到顶部

AltStyle によって変換されたページ (->オリジナル) /