0
# Template Loaders
1
2
Flexible template loading system supporting multiple sources including filesystem directories, Python packages, dictionaries, and custom loading functions. Loaders can be combined and configured for complex template discovery patterns.
3
4
## Capabilities
5
6
### FileSystem Loader
7
8
Loads templates from filesystem directories with support for multiple search paths, encoding options, and symbolic link following.
9
10
```python { .api }
11
class FileSystemLoader:
12
def __init__(self, searchpath, encoding='utf-8', followlinks=False):
13
"""
14
Initialize filesystem loader.
15
16
Parameters:
17
searchpath: Directory path or list of directory paths to search
18
encoding: Template file encoding (default: 'utf-8')
19
followlinks: Follow symbolic links (default: False)
20
"""
21
```
22
23
Usage example:
24
25
```python
26
from jinja2 import Environment, FileSystemLoader
27
28
# Single directory
29
env = Environment(loader=FileSystemLoader('templates'))
30
31
# Multiple directories
32
env = Environment(loader=FileSystemLoader(['templates', 'shared_templates']))
33
34
# With custom encoding
35
env = Environment(loader=FileSystemLoader('templates', encoding='latin-1'))
36
```
37
38
### Package Loader
39
40
Loads templates from Python package directories, useful for distributing templates within Python packages and accessing templates from installed packages.
41
42
```python { .api }
43
class PackageLoader:
44
def __init__(self, package_name, package_path='templates', encoding='utf-8'):
45
"""
46
Initialize package loader.
47
48
Parameters:
49
package_name: Python package name (e.g., 'myapp' or 'myapp.subpackage')
50
package_path: Path within package to template directory (default: 'templates')
51
encoding: Template file encoding (default: 'utf-8')
52
"""
53
```
54
55
Usage example:
56
57
```python
58
from jinja2 import Environment, PackageLoader
59
60
# Load from myapp/templates/
61
env = Environment(loader=PackageLoader('myapp'))
62
63
# Load from myapp/email_templates/
64
env = Environment(loader=PackageLoader('myapp', 'email_templates'))
65
66
# Load from installed package
67
env = Environment(loader=PackageLoader('some_third_party_package'))
68
```
69
70
### Dictionary Loader
71
72
Loads templates from a Python dictionary, useful for templates stored in memory, databases, or other non-filesystem sources.
73
74
```python { .api }
75
class DictLoader:
76
def __init__(self, mapping):
77
"""
78
Initialize dictionary loader.
79
80
Parameters:
81
mapping: Dictionary mapping template names to template source strings
82
"""
83
```
84
85
Usage example:
86
87
```python
88
from jinja2 import Environment, DictLoader
89
90
templates = {
91
'hello.html': '<h1>Hello {{ name }}!</h1>',
92
'goodbye.html': '<h1>Goodbye {{ name }}!</h1>',
93
'base.html': '''
94
<!DOCTYPE html>
95
<html>
96
<head><title>{{ title }}</title></head>
97
<body>{% block content %}{% endblock %}</body>
98
</html>
99
'''
100
}
101
102
env = Environment(loader=DictLoader(templates))
103
template = env.get_template('hello.html')
104
```
105
106
### Function Loader
107
108
Loads templates via a custom function, providing maximum flexibility for custom template sources and dynamic template generation.
109
110
```python { .api }
111
class FunctionLoader:
112
def __init__(self, load_func):
113
"""
114
Initialize function loader.
115
116
Parameters:
117
load_func: Function that takes template name and returns (source, filename, uptodate_func) tuple
118
Returns None if template doesn't exist
119
uptodate_func should return True if template is current, False if needs reloading
120
"""
121
```
122
123
Usage example:
124
125
```python
126
from jinja2 import Environment, FunctionLoader
127
import os
128
129
def load_template(name):
130
# Custom loading logic - could load from database, API, etc.
131
filepath = f'/custom/templates/{name}'
132
if os.path.exists(filepath):
133
with open(filepath, 'r') as f:
134
source = f.read()
135
# Return (source, filename, uptodate_function)
136
return source, filepath, lambda: os.path.getmtime(filepath)
137
return None
138
139
env = Environment(loader=FunctionLoader(load_template))
140
```
141
142
### Prefix Loader
143
144
Maps template name prefixes to different loaders, enabling organized template namespacing and modular template organization.
145
146
```python { .api }
147
class PrefixLoader:
148
def __init__(self, mapping, delimiter='/'):
149
"""
150
Initialize prefix loader.
151
152
Parameters:
153
mapping: Dictionary mapping prefixes to loader instances
154
delimiter: Delimiter separating prefix from template name (default: '/')
155
"""
156
```
157
158
Usage example:
159
160
```python
161
from jinja2 import Environment, PrefixLoader, FileSystemLoader, PackageLoader
162
163
loader = PrefixLoader({
164
'app': FileSystemLoader('app_templates'),
165
'admin': FileSystemLoader('admin_templates'),
166
'email': PackageLoader('myapp', 'email_templates'),
167
'shared': FileSystemLoader('shared_templates')
168
})
169
170
env = Environment(loader=loader)
171
172
# Load templates with prefixes
173
app_template = env.get_template('app/index.html')
174
admin_template = env.get_template('admin/dashboard.html')
175
email_template = env.get_template('email/welcome.html')
176
```
177
178
### Choice Loader
179
180
Tries multiple loaders in sequence until one successfully loads the template, useful for template fallback chains and migration scenarios.
181
182
```python { .api }
183
class ChoiceLoader:
184
def __init__(self, loaders):
185
"""
186
Initialize choice loader.
187
188
Parameters:
189
loaders: List of loader instances to try in order
190
"""
191
```
192
193
Usage example:
194
195
```python
196
from jinja2 import Environment, ChoiceLoader, FileSystemLoader, PackageLoader
197
198
# Try custom templates first, fall back to package defaults
199
loader = ChoiceLoader([
200
FileSystemLoader('custom_templates'),
201
FileSystemLoader('default_templates'),
202
PackageLoader('myapp', 'fallback_templates')
203
])
204
205
env = Environment(loader=loader)
206
207
# Will use first loader that has the template
208
template = env.get_template('page.html')
209
```
210
211
### Module Loader
212
213
Loads precompiled templates from Python modules, providing maximum performance by skipping template compilation at runtime.
214
215
```python { .api }
216
class ModuleLoader:
217
def __init__(self, path):
218
"""
219
Initialize module loader.
220
221
Parameters:
222
path: Import path or list of import paths to search for compiled templates
223
"""
224
```
225
226
Usage example:
227
228
```python
229
from jinja2 import Environment, ModuleLoader
230
231
# Assumes templates were precompiled to compiled_templates module
232
env = Environment(loader=ModuleLoader('compiled_templates'))
233
234
# Can also specify multiple paths
235
env = Environment(loader=ModuleLoader(['compiled_templates', 'fallback_templates']))
236
```
237
238
### Base Loader
239
240
Abstract base class for implementing custom loaders with specific loading logic and caching behavior.
241
242
```python { .api }
243
class BaseLoader:
244
def get_source(self, environment, template):
245
"""
246
Get template source, filename, and update function.
247
248
Parameters:
249
environment: Jinja2 environment instance
250
template: Template name to load
251
252
Returns:
253
tuple: (source, filename, uptodate_func) or raises TemplateNotFound
254
uptodate_func returns True if template is current
255
"""
256
257
def list_templates(self):
258
"""
259
List all available templates.
260
261
Returns:
262
list: List of template names (optional, may raise NotImplementedError)
263
"""
264
265
def load(self, environment, name, globals=None):
266
"""
267
Load and compile template.
268
269
Parameters:
270
environment: Jinja2 environment instance
271
name: Template name
272
globals: Additional globals for template
273
274
Returns:
275
Template: Compiled template instance
276
"""
277
```
278
279
## Utility Functions
280
281
```python { .api }
282
def split_template_path(template):
283
"""
284
Split template path into directory and filename components.
285
286
Parameters:
287
template: Template path string
288
289
Returns:
290
list: Path components
291
292
Raises:
293
TemplateNotFound: If template path is invalid
294
"""
295
```
296
297
## Types
298
299
```python { .api }
300
class LoaderContext:
301
"""
302
Context object passed to loader functions containing environment and template information.
303
304
Attributes:
305
environment: Jinja2 environment instance
306
template: Template name being loaded
307
filename: Template filename (if available)
308
"""
309
```