0
# Core Template Processing
1
2
Main functionality for loading Word documents as templates, rendering them with context data, and managing the template lifecycle. The DocxTemplate class provides the primary interface for all template operations.
3
4
## Capabilities
5
6
### DocxTemplate Class
7
8
The main class for managing docx files as Jinja2 templates. Handles document loading, template rendering, and output generation.
9
10
```python { .api }
11
class DocxTemplate:
12
def __init__(self, template_file: Union[IO[bytes], str, os.PathLike]) -> None:
13
"""
14
Initialize DocxTemplate with a template file.
15
16
Parameters:
17
- template_file: Path to docx template file or file-like object
18
"""
19
```
20
21
### Template Rendering
22
23
Core method for processing templates with context data using Jinja2 template engine.
24
25
```python { .api }
26
def render(self, context: Dict[str, Any], jinja_env: Optional[Environment] = None, autoescape: bool = False) -> None:
27
"""
28
Render the template with provided context data.
29
30
Parameters:
31
- context: Dictionary containing template variables and data
32
- jinja_env: Optional custom Jinja2 environment for template processing
33
- autoescape: Enable HTML/XML autoescape in Jinja2 processing
34
"""
35
```
36
37
### Document Output
38
39
Methods for saving rendered documents to files or file-like objects.
40
41
```python { .api }
42
def save(self, filename: Union[IO[bytes], str, os.PathLike], *args, **kwargs) -> None:
43
"""
44
Save the rendered document to file.
45
46
Parameters:
47
- filename: Output file path or file-like object
48
- *args, **kwargs: Additional arguments passed to python-docx save method
49
"""
50
```
51
52
### Subdocument Creation
53
54
Create new subdocuments for complex document composition scenarios.
55
56
```python { .api }
57
def new_subdoc(self, docpath=None):
58
"""
59
Create a new subdocument for insertion into the main template.
60
61
Parameters:
62
- docpath: Optional path to existing document to use as subdocument base
63
64
Returns:
65
Subdoc: New subdocument instance
66
"""
67
```
68
69
### Media Replacement
70
71
Methods for replacing media files, images, and embedded objects within templates.
72
73
```python { .api }
74
def replace_media(self, src_file, dst_file):
75
"""
76
Replace media file in template by filename.
77
78
Parameters:
79
- src_file: Source filename in template
80
- dst_file: Replacement file path
81
"""
82
83
def replace_pic(self, embedded_file, dst_file):
84
"""
85
Replace embedded picture by filename.
86
87
Parameters:
88
- embedded_file: Embedded picture filename
89
- dst_file: Replacement image file path
90
"""
91
92
def replace_embedded(self, src_file, dst_file):
93
"""
94
Replace embedded object by filename.
95
96
Parameters:
97
- src_file: Source embedded object filename
98
- dst_file: Replacement file path
99
"""
100
101
def replace_zipname(self, zipname, dst_file):
102
"""
103
Replace file by ZIP archive path.
104
105
Parameters:
106
- zipname: ZIP path within docx archive
107
- dst_file: Replacement file path
108
"""
109
```
110
111
### Replacement Management
112
113
Methods for managing and resetting media replacement operations.
114
115
```python { .api }
116
def reset_replacements(self):
117
"""
118
Reset all replacement dictionaries to empty state.
119
"""
120
```
121
122
### URL and Link Handling
123
124
Utilities for managing hyperlinks and URL references within templates.
125
126
```python { .api }
127
def build_url_id(self, url):
128
"""
129
Build URL ID for hyperlink references.
130
131
Parameters:
132
- url: URL string to process
133
134
Returns:
135
str: Generated URL ID for hyperlink reference
136
"""
137
```
138
139
### Template Analysis
140
141
Tools for analyzing template variables and validation.
142
143
```python { .api }
144
def get_undeclared_template_variables(self, jinja_env: Optional[Environment] = None, context: Optional[Dict[str, Any]] = None) -> Set[str]:
145
"""
146
Get template variables that are not declared in the provided context.
147
148
Parameters:
149
- jinja_env: Optional custom Jinja2 environment
150
- context: Optional context dictionary to check against
151
152
Returns:
153
set: Set of undeclared variable names
154
"""
155
```
156
157
### Properties
158
159
Access to template state and underlying document objects.
160
161
```python { .api }
162
@property
163
def docx:
164
"""
165
Access to underlying python-docx Document object.
166
167
Returns:
168
Document: python-docx Document instance
169
"""
170
171
@property
172
def template_file:
173
"""
174
Template file path or object.
175
176
Returns:
177
Union[str, PathLike, IO]: Original template file reference
178
"""
179
180
@property
181
def is_rendered(self) -> bool:
182
"""
183
Boolean flag indicating if template has been rendered.
184
185
Returns:
186
bool: True if render() has been called
187
"""
188
189
@property
190
def is_saved(self) -> bool:
191
"""
192
Boolean flag indicating if document has been saved.
193
194
Returns:
195
bool: True if save() has been called
196
"""
197
198
@property
199
def allow_missing_pics(self) -> bool:
200
"""
201
Boolean flag for allowing missing pictures in template.
202
203
Returns:
204
bool: Current setting for missing picture handling
205
"""
206
```
207
208
### Constants
209
210
Class constants for document relationship URIs.
211
212
```python { .api }
213
HEADER_URI: str # URI for header relationships
214
FOOTER_URI: str # URI for footer relationships
215
```
216
217
## Usage Examples
218
219
### Basic Template Processing
220
221
```python
222
from docxtpl import DocxTemplate
223
224
# Load template
225
doc = DocxTemplate("invoice_template.docx")
226
227
# Prepare data
228
context = {
229
'customer_name': 'John Doe',
230
'invoice_number': 'INV-001',
231
'items': [
232
{'description': 'Consulting', 'amount': 1000},
233
{'description': 'Development', 'amount': 2000}
234
],
235
'total': 3000
236
}
237
238
# Render and save
239
doc.render(context)
240
doc.save("invoice_001.docx")
241
```
242
243
### Custom Jinja2 Environment
244
245
```python
246
from jinja2 import Environment
247
from docxtpl import DocxTemplate
248
249
# Create custom Jinja2 environment
250
jinja_env = Environment()
251
jinja_env.filters['currency'] = lambda x: f"${x:,.2f}"
252
253
# Use with template
254
doc = DocxTemplate("financial_report.docx")
255
context = {'revenue': 150000, 'expenses': 120000}
256
doc.render(context, jinja_env=jinja_env)
257
doc.save("report.docx")
258
```
259
260
### Template Variable Validation
261
262
```python
263
from docxtpl import DocxTemplate
264
265
doc = DocxTemplate("template.docx")
266
context = {'name': 'John', 'age': 30}
267
268
# Check for missing variables
269
missing_vars = doc.get_undeclared_template_variables(context=context)
270
if missing_vars:
271
print(f"Missing template variables: {missing_vars}")
272
else:
273
doc.render(context)
274
doc.save("output.docx")
275
```