기술나눔

nunjucks는 템플릿 경로를 동적으로 업데이트합니다.

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

요청이 있을 때마다 파일을 동적으로 읽으면 특히 동시성이 높은 상황에서 성능에 일정한 영향을 미칩니다. 이 문제를 해결하려면 애플리케이션이 시작될 때 템플릿 구성을 읽고, 템플릿이 변경될 때 구성을 업데이트하여 매번 파일을 읽는 대신 애플리케이션이 시작되고 템플릿이 변경될 때만 파일을 읽으면 됩니다. 요구.

전역 변수를 사용하여 현재 템플릿 경로를 캐시하고 템플릿이 변경될 때만 변수와 파일을 업데이트할 수 있습니다.

개선된 샘플 코드는 다음과 같습니다.

디렉토리 구조 예

project
│
├── views/
│   ├── template1/
│   │   └── index.njk
│   ├── template2/
│   │   └── index.njk
│
├── config/
│   └── templateConfig.json
│
├── app.js
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

templateConfig.json 샘플 콘텐츠

{
    "currentTemplate": "template1"
}
  • 1
  • 2
  • 3

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

설명하다

  1. 전역 변수 currentTemplatePath: 현재 템플릿 경로를 캐시합니다.
  2. loadTemplateConfig 기능: 애플리케이션이 시작될 때 템플릿 구성 파일을 읽고 경로를 전역 변수에 저장합니다.
  3. configureNunjucks 기능: 캐시된 템플릿 경로를 기반으로 Nunjucks 환경을 구성합니다.
  4. 초기화 중 구성 로드: 애플리케이션이 시작될 때 호출됩니다. loadTemplateConfig 그리고configureNunjucks 기능.
  5. 템플릿 경로의 라우팅 변경: 사용자가 템플릿 경로를 변경할 때 전역 변수, 파일을 업데이트하고 Nunjucks를 재구성합니다.

이러한 방식으로 Nunjucks의 파일 및 구성은 애플리케이션이 시작되고 사용자가 템플릿 경로를 변경할 때만 읽혀 모든 요청에서 파일을 읽는 성능 문제를 방지합니다.