如何从两个不同目录(文件夹)中渲染模板?
从多目录渲染模板的常见实现方式
Flask 框架场景
- 初始化Flask应用时,通过
app.jinja_loader加载多个模板目录,或者在创建应用时指定多路径
from flask import Flask, render_template from jinja2 import FileSystemLoader app = Flask(__name__) # 同时加载home_pages和affiliate_pages两个目录 app.jinja_loader = FileSystemLoader(['./home_pages', './affiliate_pages']) # 渲染首页模板 @app.route('/home') def show_home(): return render_template('home.html') # 会按顺序在两个目录里查找home.html # 渲染联盟页模板 @app.route('/affiliate') def show_affiliate(): return render_template('affiliate.html')
- 注意:如果两个目录存在同名模板,会优先加载
FileSystemLoader列表中靠前的目录里的文件
Django 框架场景
- 修改项目
settings.py里的TEMPLATES配置,在DIRS字段添加两个模板目录的路径
# settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'home_pages', BASE_DIR / 'affiliate_pages', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
- 视图里直接调用
render函数指定模板名即可,Django会按DIRS的顺序查找模板文件
Node.js + Express(EJS引擎)场景
- 配置Express的视图目录时,传入包含两个路径的数组
const express = require('express'); const path = require('path'); const app = express(); // 设置EJS为模板引擎 app.set('view engine', 'ejs'); // 指定两个模板目录 app.set('views', [ path.join(__dirname, 'home_pages'), path.join(__dirname, 'affiliate_pages') ]); // 渲染首页 app.get('/home', (req, res) => { res.render('home', { title: '首页' }); // 自动在两个目录查找home.ejs }); // 渲染联盟页 app.get('/affiliate', (req, res) => { res.render('affiliate', { title: '联盟推广页' }); });
无框架自定义渲染场景
如果是自己实现模板渲染逻辑,核心就是遍历目录找文件,再做内容替换:
import os def render_template(template_name, template_dirs, context): # 按顺序遍历指定目录查找模板 for dir_path in template_dirs: full_path = os.path.join(dir_path, template_name) if os.path.isfile(full_path): with open(full_path, 'r', encoding='utf-8') as f: content = f.read() # 简单替换模板变量,实际场景可使用Jinja2等专业库解析语法 for key, val in context.items(): content = content.replace(f'{{{{{key}}}}}', str(val)) return content raise FileNotFoundError(f"找不到模板文件:{template_name}") # 使用示例 rendered_content = render_template('home.html', ['./home_pages', './affiliate_pages'], {'username': '访客'}) print(rendered_content)
内容的提问来源于stack exchange,提问作者benz
相关产品推荐
相关产品推荐

