0
# Structure and Layout Extras
1
2
Extensions for enhanced document structure including tables, footnotes, headers, table of contents generation, and HTML customization that improve document organization and navigation.
3
4
## Capabilities
5
6
### Table Support
7
8
Comprehensive table support with multiple syntax styles and formatting options.
9
10
```python { .api }
11
# tables extra - GitHub-flavored and PHP-Markdown Extra style tables
12
extras = ["tables"]
13
14
# wiki-tables extra - MediaWiki-style table syntax
15
extras = ["wiki-tables"]
16
17
# html-classes extra - add CSS classes to HTML elements
18
extras = {
19
"html-classes": {
20
"table": "table table-striped",
21
"thead": "table-header",
22
"code": "highlight"
23
}
24
}
25
```
26
27
**Usage Examples:**
28
29
```python
30
import markdown2
31
32
# GitHub-style tables
33
table_text = '''
34
| Name | Age | City |
35
|------|-----|------|
36
| John | 25 | NYC |
37
| Jane | 30 | LA |
38
| Bob | 35 | Chicago |
39
'''
40
41
html = markdown2.markdown(table_text, extras=["tables"])
42
43
# With custom CSS classes
44
html = markdown2.markdown(
45
table_text,
46
extras={
47
"tables": None,
48
"html-classes": {
49
"table": "table table-bordered table-striped",
50
"thead": "table-dark"
51
}
52
}
53
)
54
55
# Wiki-style tables
56
wiki_table = '''
57
{| class="wikitable"
58
|-
59
! Name !! Age !! City
60
|-
61
| John || 25 || NYC
62
|-
63
| Jane || 30 || LA
64
|}
65
'''
66
67
html = markdown2.markdown(wiki_table, extras=["wiki-tables"])
68
```
69
70
### Footnotes System
71
72
Comprehensive footnote support with customizable formatting and back-references.
73
74
```python { .api }
75
# footnotes extra - support footnotes with back-references
76
extras = ["footnotes"]
77
78
# With custom configuration
79
extras = ["footnotes"]
80
footnote_title = "Jump back to footnote"
81
footnote_return_symbol = "↩"
82
```
83
84
**Usage Examples:**
85
86
```python
87
import markdown2
88
89
footnote_text = '''
90
This is a statement with a footnote[^1].
91
92
Here's another statement[^note].
93
94
[^1]: This is the first footnote.
95
96
[^note]: This is a named footnote with more detail.
97
It can span multiple paragraphs.
98
99
Like this one.
100
'''
101
102
html = markdown2.markdown(
103
footnote_text,
104
extras=["footnotes"],
105
footnote_title="Return to text",
106
footnote_return_symbol="⤴"
107
)
108
```
109
110
### Header Enhancement
111
112
Add IDs and navigation anchors to headers for document navigation.
113
114
```python { .api }
115
# header-ids extra - add "id" attributes to headers
116
extras = ["header-ids"]
117
118
# tag-friendly extra - require space between # and header text
119
extras = ["tag-friendly"]
120
121
# With configuration options
122
extras = {
123
"header-ids": {
124
"prefix": "section-", # Prefix for header IDs
125
"mixed": False, # Use mixed case (default: False)
126
"reset-count": True # Reset counter for each document
127
}
128
}
129
```
130
131
**Usage Examples:**
132
133
```python
134
import markdown2
135
136
header_text = '''
137
# Introduction
138
This is the introduction section.
139
140
## Getting Started
141
How to get started with the project.
142
143
### Installation
144
Step-by-step installation guide.
145
146
## Configuration
147
Configuration options and examples.
148
'''
149
150
html = markdown2.markdown(header_text, extras=["header-ids"])
151
# Generates: <h1 id="introduction">Introduction</h1>
152
153
# With custom prefix
154
html = markdown2.markdown(
155
header_text,
156
extras={"header-ids": {"prefix": "doc-"}}
157
)
158
# Generates: <h1 id="doc-introduction">Introduction</h1>
159
160
# Tag-friendly mode (requires space after #)
161
tag_text = '''
162
# Valid Header (space after #)
163
#Invalid Header (no space - won't be processed as header)
164
'''
165
html = markdown2.markdown(tag_text, extras=["tag-friendly"])
166
```
167
168
### Table of Contents Generation
169
170
Automatic table of contents generation with customizable depth and formatting.
171
172
```python { .api }
173
# toc extra - generate table of contents (implies header-ids)
174
extras = ["toc"]
175
176
# With depth configuration
177
extras = {
178
"toc": {
179
"depth": 3 # Include headers up to h3 level
180
}
181
}
182
```
183
184
**Usage Examples:**
185
186
```python
187
import markdown2
188
189
document_text = '''
190
# Chapter 1: Introduction
191
Content for chapter 1.
192
193
## Section 1.1: Overview
194
Overview content.
195
196
### Subsection 1.1.1: Details
197
Detailed content.
198
199
## Section 1.2: Getting Started
200
Getting started content.
201
202
# Chapter 2: Advanced Topics
203
Advanced content.
204
'''
205
206
html = markdown2.markdown(document_text, extras=["toc"])
207
208
# Access the generated table of contents
209
if hasattr(html, 'toc_html') and html.toc_html:
210
print("Table of Contents HTML:")
211
print(html.toc_html)
212
213
# With custom depth
214
html = markdown2.markdown(
215
document_text,
216
extras={"toc": {"depth": 2}} # Only h1 and h2
217
)
218
```
219
220
### Document Metadata
221
222
Extract and process document metadata from YAML front matter.
223
224
```python { .api }
225
# metadata extra - extract YAML-style metadata from document header
226
extras = ["metadata"]
227
```
228
229
**Usage Examples:**
230
231
```python
232
import markdown2
233
234
document_with_metadata = '''---
235
title: My Document
236
author: John Doe
237
date: 2023-01-15
238
tags: [markdown, documentation, tutorial]
239
draft: false
240
---
241
242
# Document Content
243
244
This is the actual document content that follows the metadata.
245
'''
246
247
html = markdown2.markdown(document_with_metadata, extras=["metadata"])
248
249
# Access extracted metadata
250
if hasattr(html, 'metadata') and html.metadata:
251
print(f"Title: {html.metadata['title']}")
252
print(f"Author: {html.metadata['author']}")
253
print(f"Date: {html.metadata['date']}")
254
print(f"Tags: {html.metadata['tags']}")
255
print(f"Draft: {html.metadata['draft']}")
256
```
257
258
### HTML Processing Integration
259
260
Process markdown within HTML blocks and add custom CSS classes.
261
262
```python { .api }
263
# markdown-in-html extra - process markdown inside HTML blocks
264
extras = ["markdown-in-html"]
265
266
# html-classes extra - add CSS classes to generated HTML elements
267
extras = {
268
"html-classes": {
269
"img": "img-responsive",
270
"table": "table table-striped",
271
"pre": "prettyprint",
272
"code": "highlight",
273
"ul": "list-unstyled",
274
"ol": "numbered-list"
275
}
276
}
277
```
278
279
**Usage Examples:**
280
281
```python
282
import markdown2
283
284
# Markdown inside HTML
285
html_with_markdown = '''
286
<div class="content">
287
<markdown="1">
288
## This is a header inside HTML
289
290
This **bold text** and *italic text* will be processed.
291
292
- List item 1
293
- List item 2
294
</markdown>
295
</div>
296
'''
297
298
html = markdown2.markdown(html_with_markdown, extras=["markdown-in-html"])
299
300
# Adding CSS classes to elements
301
content = '''
302

303
304
| Col 1 | Col 2 |
305
|-------|-------|
306
| Data | More |
307
308
```python
309
code here
310
```
311
'''
312
313
html = markdown2.markdown(
314
content,
315
extras={
316
"tables": None,
317
"fenced-code-blocks": None,
318
"html-classes": {
319
"img": "img-fluid rounded",
320
"table": "table table-hover",
321
"pre": "bg-light p-3",
322
"code": "text-primary"
323
}
324
}
325
)
326
```
327
328
## Advanced Structure Processing
329
330
### Complete Document Processing
331
332
Combine multiple structure extras for comprehensive document processing:
333
334
```python
335
import markdown2
336
337
# Academic paper or technical documentation setup
338
academic_processor = markdown2.Markdown(
339
extras={
340
"metadata": None, # YAML front matter
341
"toc": {"depth": 4}, # Deep table of contents
342
"header-ids": { # Prefixed header IDs
343
"prefix": "sec-",
344
"reset-count": True
345
},
346
"footnotes": None, # Academic citations
347
"tables": None, # Data tables
348
"fenced-code-blocks": None, # Code examples
349
"html-classes": { # Bootstrap styling
350
"table": "table table-striped table-bordered",
351
"img": "img-fluid figure-img",
352
"pre": "bg-light p-3 rounded"
353
}
354
},
355
footnote_title="Return to reference",
356
footnote_return_symbol="↩"
357
)
358
359
# Process academic document
360
html = academic_processor.convert(academic_document)
361
362
# Access all generated content
363
print("Main content length:", len(html))
364
if html.metadata:
365
print("Document metadata:", html.metadata)
366
if html.toc_html:
367
print("Table of contents available")
368
```
369
370
### Blog/CMS Integration
371
372
Structure extras for content management systems:
373
374
```python
375
import markdown2
376
377
# Blog post processor
378
blog_processor = markdown2.Markdown(
379
extras={
380
"metadata": None, # Post metadata (title, date, tags)
381
"header-ids": None, # Anchor links
382
"tables": None, # Content tables
383
"footnotes": None, # References
384
"break-on-newline": None, # GitHub-style breaks
385
"smarty-pants": None, # Typography
386
"html-classes": { # Custom styling
387
"table": "post-table",
388
"img": "post-image",
389
"pre": "post-code"
390
}
391
}
392
)
393
394
blog_html = blog_processor.convert(blog_post_markdown)
395
396
# Extract metadata for CMS
397
if blog_html.metadata:
398
post_title = blog_html.metadata.get('title', 'Untitled')
399
post_tags = blog_html.metadata.get('tags', [])
400
post_date = blog_html.metadata.get('date')
401
```
402
403
### GitHub Task Lists
404
405
GitHub-style task lists with checkboxes for todo items and interactive elements.
406
407
```python { .api }
408
# task_list extra - GitHub-style task lists
409
extras = ["task_list"]
410
```
411
412
**Usage Examples:**
413
414
```python
415
import markdown2
416
417
task_content = '''
418
## Todo List
419
420
- [x] Completed task
421
- [ ] Incomplete task
422
- [x] Another completed item
423
- [ ] Still need to do this
424
425
## Project Status
426
427
- [x] Research phase complete
428
- [x] Design approved
429
- [ ] Implementation in progress
430
- [ ] Testing pending
431
- [ ] Documentation needed
432
'''
433
434
html = markdown2.markdown(task_content, extras=["task_list"])
435
# Converts to HTML with checkbox inputs
436
```
437
438
### XML Processing
439
440
Support for XML processing instructions and namespaced XML tags.
441
442
```python { .api }
443
# xml extra - XML processing support
444
extras = ["xml"]
445
```
446
447
### Header Level Adjustment
448
449
Adjust header levels by demoting them by a specified number of levels.
450
451
```python { .api }
452
# demote-headers extra - demote header levels
453
extras = {"demote-headers": 1} # Demote by 1 level (H1 becomes H2, etc.)
454
```
455
456
**Usage Examples:**
457
458
```python
459
import markdown2
460
461
# Original headers: H1, H2, H3
462
content = '''
463
# Main Title
464
## Section Title
465
### Subsection
466
'''
467
468
# Demote all headers by 2 levels
469
html = markdown2.markdown(content, extras={"demote-headers": 2})
470
# Results in: H3, H4, H5
471
```
472
473
## Configuration Reference
474
475
### Header IDs Configuration
476
477
```python
478
header_config = {
479
"prefix": "", # Prefix for generated IDs
480
"mixed": False, # Preserve mixed case in IDs
481
"reset-count": True # Reset counter for each conversion
482
}
483
```
484
485
### TOC Configuration
486
487
```python
488
toc_config = {
489
"depth": 6 # Maximum header level to include (1-6)
490
}
491
```
492
493
### HTML Classes Configuration
494
495
```python
496
html_classes_config = {
497
"img": "css-class-for-images",
498
"table": "css-class-for-tables",
499
"thead": "css-class-for-table-headers",
500
"pre": "css-class-for-code-blocks",
501
"code": "css-class-for-inline-code",
502
"ul": "css-class-for-unordered-lists",
503
"ol": "css-class-for-ordered-lists"
504
}
505
```
506
507
### Integration with Web Frameworks
508
509
```python
510
import markdown2
511
512
# Flask/Django integration example
513
def render_markdown_post(markdown_content):
514
processor = markdown2.Markdown(
515
extras={
516
"metadata": None,
517
"toc": {"depth": 3},
518
"header-ids": None,
519
"tables": None,
520
"footnotes": None,
521
"html-classes": {
522
"table": "table table-striped",
523
"img": "img-responsive"
524
}
525
}
526
)
527
528
html = processor.convert(markdown_content)
529
530
return {
531
'content': str(html),
532
'metadata': getattr(html, 'metadata', {}),
533
'toc': getattr(html, 'toc_html', None)
534
}
535
```