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,你应该能够看到渲染后的模板页面,显示了从服务器发送的数据。

posted @ 2024-04-04 21:00  C羽言  阅读(158)  评论(0)    收藏  举报