Nodejs中在jade模板怎么使用 underscore的方法呢?
Nodejs中在jade模板怎么使用 underscore的方法呢?
在jade模板中怎么使用 node版的 underscore的方法呢?
‘_’ 方法传递给了 jade 模板, 但是jade模板什么的不能换行,分号,之类的。。。
Node.js 中在 Jade 模板中如何使用 Underscore 的方法?
在 Node.js 中使用 Jade(现在称为 Pug)模板引擎时,有时你可能希望利用 Underscore 库的强大功能来处理一些数据。然而,Jade 模板语法本身非常简洁,不支持直接使用 JavaScript 语句如 ;
或者换行符。因此,你需要通过一些技巧来实现这一点。
示例背景
假设你有一个简单的数组,并且你想使用 Underscore 库中的某个方法(比如 _.map
)来处理这个数组,然后在 Jade 模板中显示结果。
安装依赖
首先,确保你已经安装了 underscore
和 pug
:
npm install underscore pug --save
服务器端代码
接下来,在你的 Node.js 服务器端代码中,你可以将 Underscore 的引用传递给模板引擎:
const express = require('express');
const app = express();
const _ = require('underscore');
app.get('/', (req, res) => {
const data = [1, 2, 3, 4, 5];
const mappedData = _.map(data, num => num * 2); // 使用 Underscore 映射数组
res.render('index', { mappedData });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Jade 模板代码
然后,在你的 Jade 模板文件中(例如 views/index.pug
),你可以这样使用映射后的数据:
doctype html
html
head
title= 'Underscore in Jade'
body
ul
each item in mappedData
li= item
解释
- 服务器端:我们创建了一个简单的 Express 应用,并使用 Underscore 将数组
[1, 2, 3, 4, 5]
映射为[2, 4, 6, 8, 10]
。 - 模板:在 Jade 模板中,我们遍历
mappedData
数组,并将其每一项显示为一个列表项。注意,Jade 不需要;
或者{}
来定义语句块,它依赖于缩进。
通过这种方式,你可以在 Node.js 的 Jade/Pug 模板中充分利用 Underscore 的强大功能,而不需要直接在模板中写复杂的 JavaScript 逻辑。
http://expressjs.com/api.html#app.locals
js
var app = express()
app.locals.moment = require('moment-timezone')
jade
span.time= moment(time.time).tz('Asia/Shanghai').format('HH:mm')
可能在使用中需要比较多的方法套用,会新建些变量 , 换行会导致jade报错, 不换行可读性比较差
_.each(arr, function(num){ var new_arr = []; _.each(num, function(literal){ new_arr.push(num.split(’.’).pop()); }); });
在Node.js中使用Jade模板引擎(现称为Pug)与Underscore.js时,可以直接通过将Underscore对象传递给Jade模板来实现。这样你就可以在模板中直接调用Underscore的方法了。以下是如何实现这一点的示例。
示例代码
首先,确保安装了jade
和underscore
:
npm install jade underscore
接下来是服务器端代码:
const jade = require('jade');
const _ = require('underscore');
const compiledFunction = jade.compile(`
doctype html
html
head
title= pageTitle
body
h1= greetUser(user)
ul
each val in users
li= val.name
`, {
client: false, // 客户端编译
filename: 'template.jade',
locals: {
// 将Underscore对象传递给模板
_: _
}
});
const result = compiledFunction({
pageTitle: 'My Page',
user: 'John Doe',
users: [
{ name: 'Alice' },
{ name: 'Bob' }
]
});
console.log(result);
在上面的代码中,我们创建了一个包含Jade模板字符串的变量,并且在locals
选项中将Underscore对象传递给模板。然后,我们调用了编译后的函数,并传入了一些数据。在模板中,你可以像这样使用Underscore方法:
- var filteredUsers = _.filter(users, function(user) { return user.name.startsWith('A'); })
ul
each user in filteredUsers
li= user.name
这里我们使用了_.filter()
方法来过滤出名字以"A"开头的用户。
注意事项
- Jade模板不支持直接在模板中使用分号或换行符。所有表达式都应该在一个连续的行中。
- 在模板中,使用
-
符号开始表示这是一个JavaScript语句,而不是输出内容。 - 使用
=
符号开始表示输出结果到模板中。
通过这种方式,你可以在Jade/Pug模板中利用Underscore的强大功能进行数据处理。