欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > nunjucks动态更新模版路径

nunjucks动态更新模版路径

2024/10/24 1:49:02 来源:https://blog.csdn.net/weixin_57097753/article/details/140257406  浏览:    关键词:nunjucks动态更新模版路径

每次请求都动态读取文件确实会有一定的性能影响,特别是在高并发的情况下。为了解决这个问题,可以在应用启动时读取模板配置,并在模板更改时更新配置,这样只需要在应用启动和模板更改时读取文件,而不是每次请求都读取文件。

可以使用一个全局变量来缓存当前的模板路径,只有在更改模板时才更新该变量和文件。

以下是改进后的示例代码:

目录结构示例

project
│
├── views/
│   ├── template1/
│   │   └── index.njk
│   ├── template2/
│   │   └── index.njk
│
├── config/
│   └── templateConfig.json
│
├── app.js

templateConfig.json 示例内容

{"currentTemplate": "template1"
}

app.js 示例代码

const express = require('express');
const nunjucks = require('nunjucks');
const path = require('path');
const fs = require('fs');const app = express();// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));// 全局变量,缓存当前模板路径
let currentTemplatePath;// 读取配置文件中的当前模板路径
function loadTemplateConfig() {const config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config/templateConfig.json'), 'utf8'));currentTemplatePath = config.currentTemplate;
}// 配置Nunjucks环境
function configureNunjucks() {nunjucks.configure(path.join(__dirname, `views/${currentTemplatePath}`), {autoescape: false,noCache: true,express: app});
}// 初始化时加载配置
loadTemplateConfig();
configureNunjucks();// 路由
app.get('/', (req, res) => {res.render('index.njk', { title: 'Hello Nunjucks!' });
});// 路由:更改模板路径
app.get('/change-template', (req, res) => {const newTemplate = req.query.template;if (newTemplate) {currentTemplatePath = newTemplate;const config = { currentTemplate: newTemplate };fs.writeFileSync(path.join(__dirname, 'config/templateConfig.json'), JSON.stringify(config), 'utf8');configureNunjucks(); // 更新Nunjucks配置res.send(`Template changed to ${newTemplate}`);} else {res.send('No template specified');}
});// 启动服务器
const port = 3000;
app.listen(port, () => {console.log(`服务器已启动,访问地址:http://localhost:${port}`);
});

解释

  1. 全局变量 currentTemplatePath:缓存当前的模板路径。
  2. loadTemplateConfig 函数:在应用启动时读取模板配置文件,并将路径保存到全局变量中。
  3. configureNunjucks 函数:根据缓存的模板路径配置Nunjucks环境。
  4. 初始化时加载配置:在应用启动时调用 loadTemplateConfigconfigureNunjucks 函数。
  5. 更改模板路径的路由:当用户更改模板路径时,更新全局变量、文件并重新配置Nunjucks。

通过这种方式,只有在应用启动和用户更改模板路径时才会读取文件和配置Nunjucks,避免了每次请求都读取文件的性能问题。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com