0
# Advanced Block Extensions
1
2
Extensions using the generic blocks framework for creating structured content including admonitions, captions, definitions, tabbed interfaces, HTML blocks, and other advanced block-level elements.
3
4
## Capabilities
5
6
### Blocks Framework
7
8
Generic block processing framework that provides the foundation for all block-based extensions with consistent syntax and extensible architecture.
9
10
```python { .api }
11
def makeExtension(**kwargs):
12
"""
13
Create base Blocks extension for generic block processing.
14
15
Returns:
16
BlocksExtension instance
17
"""
18
19
class BlocksExtension(Extension):
20
"""Base blocks framework extension."""
21
22
class BlocksMgrExtension(Extension):
23
"""Blocks manager extension for coordinating block processing."""
24
25
class BlocksProcessor(BlockProcessor):
26
"""Generic block processor."""
27
28
class BlocksTreeprocessor(Treeprocessor):
29
"""Blocks tree processor for post-processing."""
30
31
class BlockEntry:
32
"""Block entry tracking class."""
33
34
def get_frontmatter(text):
35
"""
36
Parse YAML frontmatter from text.
37
38
Parameters:
39
- text: str - Input text with potential frontmatter
40
41
Returns:
42
tuple - (frontmatter_dict, remaining_text)
43
"""
44
45
def reindent(text, indent_level=0):
46
"""
47
Reindent text to specified level.
48
49
Parameters:
50
- text: str - Text to reindent
51
- indent_level: int - Target indentation level
52
53
Returns:
54
str - Reindented text
55
"""
56
57
def unescape_markdown(text):
58
"""
59
Unescape markdown placeholders.
60
61
Parameters:
62
- text: str - Text with escaped markdown
63
64
Returns:
65
str - Unescaped text
66
"""
67
```
68
69
### Block Base Class
70
71
Abstract base class for all block implementations providing consistent interface and type validation.
72
73
```python { .api }
74
class Block:
75
"""
76
Abstract base class for all block implementations.
77
78
Provides standard interface and validation utilities.
79
"""
80
81
def __init__(self, **kwargs):
82
"""Initialize block with configuration."""
83
84
def run(self, content, **kwargs):
85
"""Process block content and return HTML."""
86
87
# Type validation functions
88
def type_multi(*validators):
89
"""Validate against multiple type validators."""
90
91
def type_any():
92
"""Accept any type."""
93
94
def type_none():
95
"""Accept None/null values."""
96
97
def type_bool():
98
"""Validate boolean type."""
99
100
def type_string():
101
"""Validate string type."""
102
103
def type_integer():
104
"""Validate integer type."""
105
106
def type_float():
107
"""Validate float type."""
108
109
def type_list():
110
"""Validate list type."""
111
112
def type_dict():
113
"""Validate dictionary type."""
114
```
115
116
### Admonition Blocks
117
118
Create callout boxes and admonitions with various styles for notes, warnings, tips, and other highlighted content.
119
120
```python { .api }
121
class Admonition(Block):
122
"""
123
Admonition block for creating styled callout boxes.
124
125
Supports various admonition types: note, warning, tip, danger, info, etc.
126
"""
127
128
def run(self, content, type="note", title=None, **kwargs):
129
"""
130
Process admonition block content.
131
132
Parameters:
133
- content: str - Block content
134
- type: str - Admonition type ('note', 'warning', 'tip', etc.)
135
- title: str - Optional custom title
136
137
Returns:
138
str - Rendered admonition HTML
139
"""
140
```
141
142
**Usage Example:**
143
144
```python
145
import markdown
146
147
md = markdown.Markdown(extensions=['pymdownx.blocks.admonition'])
148
149
text = '''
150
!!! note "Important Information"
151
152
This is a note admonition with a custom title.
153
154
!!! warning
155
156
This is a warning without a custom title.
157
158
!!! tip "Pro Tip"
159
160
This is a helpful tip for users.
161
'''
162
html = md.convert(text)
163
```
164
165
### Details Blocks
166
167
Advanced collapsible content blocks with more features than the basic details extension.
168
169
```python { .api }
170
class Details(Block):
171
"""
172
Advanced details block for collapsible content.
173
174
Provides enhanced functionality over basic details extension.
175
"""
176
177
def run(self, content, summary="Details", open=False, **kwargs):
178
"""
179
Process details block content.
180
181
Parameters:
182
- content: str - Block content
183
- summary: str - Summary text for the details element
184
- open: bool - Whether details should start expanded
185
186
Returns:
187
str - Rendered details HTML
188
"""
189
```
190
191
### Tab Blocks
192
193
Advanced tabbed interfaces with enhanced functionality and styling options.
194
195
```python { .api }
196
class Tab(Block):
197
"""
198
Tab block for creating tabbed interfaces.
199
200
Provides advanced tabbed content functionality.
201
"""
202
203
def run(self, content, title, **kwargs):
204
"""
205
Process tab block content.
206
207
Parameters:
208
- content: str - Tab content
209
- title: str - Tab title
210
211
Returns:
212
str - Rendered tab HTML
213
"""
214
215
class TabbedTreeprocessor(Treeprocessor):
216
"""Tabbed content tree processor for tab group coordination."""
217
```
218
219
**Usage Example:**
220
221
```python
222
import markdown
223
224
md = markdown.Markdown(extensions=['pymdownx.blocks.tab'])
225
226
text = '''
227
/// tab | Python
228
```python
229
print("Hello from Python!")
230
```
231
///
232
233
/// tab | JavaScript
234
```javascript
235
console.log("Hello from JavaScript!");
236
```
237
///
238
239
/// tab | Bash
240
```bash
241
echo "Hello from Bash!"
242
```
243
///
244
'''
245
html = md.convert(text)
246
```
247
248
### Caption Blocks
249
250
Add captions to figures, tables, and other content elements with proper semantic markup.
251
252
```python { .api }
253
class Caption(Block):
254
"""
255
Caption block for adding captions to content elements.
256
257
Provides semantic caption markup for figures and tables.
258
"""
259
260
def run(self, content, type="figure", **kwargs):
261
"""
262
Process caption block content.
263
264
Parameters:
265
- content: str - Caption content
266
- type: str - Caption type ('figure', 'table', etc.)
267
268
Returns:
269
str - Rendered caption HTML
270
"""
271
```
272
273
### Definition Blocks
274
275
Create definition lists and glossary entries with enhanced formatting.
276
277
```python { .api }
278
class Definition(Block):
279
"""
280
Definition block for creating definition lists and glossaries.
281
282
Provides enhanced definition list functionality.
283
"""
284
285
def run(self, content, term, **kwargs):
286
"""
287
Process definition block content.
288
289
Parameters:
290
- content: str - Definition content
291
- term: str - Term being defined
292
293
Returns:
294
str - Rendered definition HTML
295
"""
296
```
297
298
### HTML Blocks
299
300
Raw HTML content blocks with safety features and validation.
301
302
```python { .api }
303
class HTML(Block):
304
"""
305
HTML block for raw HTML content.
306
307
Provides controlled HTML content insertion with safety features.
308
"""
309
310
def run(self, content, validate=True, **kwargs):
311
"""
312
Process HTML block content.
313
314
Parameters:
315
- content: str - Raw HTML content
316
- validate: bool - Whether to validate HTML
317
318
Returns:
319
str - Processed HTML content
320
"""
321
```
322
323
## Block Syntax Patterns
324
325
### Generic Block Syntax
326
327
All blocks follow a consistent syntax pattern:
328
329
```
330
/// block-type | title
331
Block content goes here
332
///
333
334
/// block-type
335
attribute: value
336
another: value
337
338
Block content with YAML frontmatter
339
///
340
```
341
342
### Admonition Syntax
343
344
```
345
!!! note "Optional Title"
346
347
Admonition content
348
349
!!! warning
350
351
Warning content without custom title
352
353
!!! danger "Critical Alert"
354
355
Danger admonition with custom title
356
```
357
358
### Tab Group Syntax
359
360
```
361
/// tab | Tab 1 Title
362
363
Content for first tab
364
365
///
366
367
/// tab | Tab 2 Title
368
369
Content for second tab
370
371
///
372
```
373
374
### Details Syntax
375
376
```
377
/// details | Summary Text
378
open: true
379
380
Collapsible content that starts expanded
381
382
///
383
384
/// details | Click to Expand
385
386
Content that starts collapsed
387
388
///
389
```
390
391
## Advanced Block Configuration
392
393
### Block Registration
394
395
```python
396
from pymdownx.blocks import block
397
398
# Register custom block
399
@block.register('custom')
400
class CustomBlock(Block):
401
def run(self, content, **kwargs):
402
return f'<div class="custom">{content}</div>'
403
```
404
405
### YAML Frontmatter Support
406
407
```python
408
text = '''
409
/// admonition
410
type: warning
411
title: "Custom Warning"
412
413
This admonition uses YAML frontmatter for configuration.
414
///
415
'''
416
```
417
418
### Nested Block Support
419
420
```python
421
text = '''
422
/// details | Outer Details
423
424
/// tab | Inner Tab 1
425
426
Content in nested tab
427
428
///
429
430
/// tab | Inner Tab 2
431
432
More nested content
433
434
///
435
436
///
437
'''
438
```
439
440
## Block Validation and Type Safety
441
442
### Custom Validators
443
444
```python
445
from pymdownx.blocks.block import type_string, type_bool, type_integer
446
447
class CustomBlock(Block):
448
config = {
449
'title': type_string(),
450
'enabled': type_bool(),
451
'count': type_integer()
452
}
453
```
454
455
### Multi-Type Validation
456
457
```python
458
from pymdownx.blocks.block import type_multi, type_string, type_none
459
460
class FlexibleBlock(Block):
461
config = {
462
'optional_title': type_multi(type_string(), type_none())
463
}
464
```
465
466
## Integration with Other Extensions
467
468
### Combining Blocks with Other Extensions
469
470
```python
471
md = markdown.Markdown(extensions=[
472
'pymdownx.blocks.admonition',
473
'pymdownx.blocks.tab',
474
'pymdownx.superfences',
475
'pymdownx.highlight'
476
])
477
```
478
479
### Block Content Processing
480
481
Blocks can contain other markdown extensions:
482
483
```python
484
text = '''
485
!!! note "Code Example"
486
487
```python
488
def hello():
489
print("Hello from inside an admonition!")
490
```
491
492
This code block is processed by SuperFences within the admonition.
493
'''
494
```
495
496
## Types
497
498
```python { .api }
499
from typing import Any, Callable, Dict, List, Optional, Union
500
from markdown import Extension, BlockProcessor, Treeprocessor
501
502
# Block-related types
503
BlockConfig = Dict[str, Any] # Block configuration dictionary
504
BlockValidator = Callable[[Any], bool] # Type validator function
505
BlockContent = str # Block content string
506
BlockAttributes = Dict[str, Any] # Block attribute dictionary
507
508
# YAML frontmatter types
509
Frontmatter = Dict[str, Any] # Parsed YAML frontmatter
510
FrontmatterTuple = tuple[Frontmatter, str] # (frontmatter, content) tuple
511
512
# Block processing types
513
BlockResult = str # Processed block HTML result
514
IndentLevel = int # Text indentation level
515
```