Berbagi teknologi

nunjucks secara dinamis memperbarui jalur template

2024-07-12

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

Membaca file secara dinamis dengan setiap permintaan memang memiliki dampak kinerja tertentu, terutama dalam situasi konkurensi tinggi. Untuk mengatasi masalah ini, Anda dapat membaca konfigurasi template saat aplikasi dimulai, dan memperbarui konfigurasi saat template berubah, sehingga file hanya perlu dibaca saat aplikasi dimulai dan template berubah, alih-alih membaca file setiap saat. meminta.

Anda dapat menggunakan variabel global untuk menyimpan cache jalur templat saat ini dan hanya memperbarui variabel dan file ketika templat diubah.

Berikut ini contoh kode yang ditingkatkan:

Contoh struktur direktori

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 Contoh konten

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

app.js Kode sampel

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

menjelaskan

  1. variabel global currentTemplatePath: Cache jalur templat saat ini.
  2. loadTemplateConfig fungsi: Membaca file konfigurasi templat saat aplikasi dimulai dan menyimpan jalur ke variabel global.
  3. configureNunjucks fungsi: Konfigurasikan lingkungan Nunjucks berdasarkan jalur templat yang di-cache.
  4. Muat konfigurasi selama inisialisasi: Dipanggil ketika aplikasi dimulai loadTemplateConfig DanconfigureNunjucks fungsi.
  5. Ubah perutean untuk jalur templat: Perbarui variabel global, file, dan konfigurasi ulang Nunjucks saat pengguna mengubah jalur templat.

Dengan cara ini, file dan konfigurasi Nunjucks hanya dibaca ketika aplikasi dimulai dan pengguna mengubah jalur template, menghindari masalah kinerja dalam membaca file pada setiap permintaan.