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,避免了每次请求都读取文件的性能问题。

相关推荐

  1. nunjucks动态更新模版路径

    2024-07-09 17:50:11       25 阅读
  2. 在 PyTorch 中动态构建和更新模型

    2024-07-09 17:50:11       57 阅读
  3. c#实现23种常见的设计模式--动态更新

    2024-07-09 17:50:11       19 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 17:50:11       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 17:50:11       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 17:50:11       58 阅读
  4. Python语言-面向对象

    2024-07-09 17:50:11       69 阅读

热门阅读

  1. 【python技巧】pytorch网络可视化

    2024-07-09 17:50:11       29 阅读
  2. 单例模式的实现

    2024-07-09 17:50:11       22 阅读
  3. 【MIT 6.5840/6.824】Lab1 MapReduce

    2024-07-09 17:50:11       21 阅读
  4. 【云原生】Kubernetes之持久化

    2024-07-09 17:50:11       22 阅读
  5. urlib Python爬虫

    2024-07-09 17:50:11       29 阅读
  6. 【MySQL】SQL中的DROP、DELETE和TRUNCATE的区别

    2024-07-09 17:50:11       37 阅读
  7. 云原生监控-Kubernetes-Promethues-Grafana

    2024-07-09 17:50:11       30 阅读
  8. arm (exti中断)

    2024-07-09 17:50:11       29 阅读
  9. LRU Cache 双向链表以及STL list实现----面试常考

    2024-07-09 17:50:11       31 阅读