Technology sharing

nunjucks dynamically updates template iter

2024-07-12

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

Dynamice legens tabella cum unaquaque petitione certum effectum habet ictum, praesertim in magnis concurrentibus condicionibus. Ad hanc quaestionem solvendam, figuram formulam legere potes cum applicatione incipit, ac conformationem renova cum Formulae mutationibus, ut tabella tantum legi debet cum application incipit et Formulae mutationes, loco tabellae in singulis legendis. rogamus.

Variabilis globali uti potes, ut semita hodiernam templates cacheriam et solum variabilem ac limam innovare cum Formula mutatur.

Exemplar hic emendavit codicem:

Exemplum structurae Directory

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 Sample content

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

app.js Sample code

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

explicare

  1. global variabiles currentTemplatePath: Cache the current template iter.
  2. loadTemplateConfig officium: Formulae configurationis lima, cum application incipit et viam ad global variabilem servabit.
  3. configureNunjucks officium: Nunjucks configurare environment in fundamento template in via.
  4. Configuratione in load initialization: Appellatus cum applicatione incipit loadTemplateConfig etconfigureNunjucks officium.
  5. Mutare profectus ad template semitas: Renova variabiles global, fasciculi et reconfigure Nunjucks, cum usor iter Formulae mutat.

Hoc modo, tabella et configuratione Nunjucks tantum legunt cum application incipit ac user mutat viam Formulae, vitando problema perficiendi tabellam in omni petitione legendi.