nodejs中使用Nunjucks 模板引擎
简单示例
const nunjucks = require('nunjucks');
// 配置 Nunjucks 环境
nunjucks.configure('views', {
autoescape: true, //自动转义功能 默认为true 可以不写
});
// 渲染模板
nunjucks.render('index.html', { title: '<span>Hello World</span>', content: 'Welcome to my website!' }, function(err, html) {
if (err) {
// 处理错误
console.error(err);
return;
}
// 打印渲染后的 HTML
console.log(html);
});
在koa中使用
const Koa = require('koa');
const nunjucks = require('nunjucks');
const app = new Koa();
// 配置 Nunjucks
nunjucks.configure(__dirname + '/views', {
autoescape: true, // 是否自动转义输出
noCache: true // 是否禁用模板缓存,方便开发调试
});
// 将 Nunjucks 添加为 Koa 中间件
app.use(async (ctx, next) => {
ctx.render = nunjucks.render;
await next();
});
app.use(async (ctx) => {
// 使用 ctx.render 渲染模板文件
ctx.body = await ctx.render('index.html', { title: 'Koa with Nunjucks', content: 'hello world!' });
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
koa-nunjucks-2 模块
const Koa = require('koa');
const nunjucks = require('koa-nunjucks-2');
const app = new Koa();
// 设置 Nunjucks 模板引擎
app.use(nunjucks({
ext: 'html', // 模板文件的扩展名
path: __dirname + '/views', // 模板文件的存放路径
nunjucksConfig: {
autoescape: true, // 是否自动转义输出
noCache: true // 是否禁用模板缓存,方便开发调试
}
}));
// 设置路由
app.use(async ctx => {
await ctx.render('index', { title: 'Koa with Nunjucks' ,message:'hello world!'});
});
// 启动服务器
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
接下来,在项目根目录下创建一个名为 views
的文件夹,并在其中创建一个名为 index.html
的模板文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</body>
</html>
最后,在命令行中运行以下命令启动应用:
node app.js
现在,打开浏览器并访问 http://localhost:3000
,你应该能够看到渲染后的模板页面,显示了从服务器发送的数据。
分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具