0
# Template Functions
1
2
Custom Jinja2 functions and template modifications that enhance template rendering with canonical URL fixes, directory builder support, and improved template context management for better SEO and navigation.
3
4
## Capabilities
5
6
### Jinja2 Template Setup
7
8
Main function that registers custom template functions and fixes builder-specific issues.
9
10
```python { .api }
11
def setup_jinja(app: Sphinx, pagename: str, templatename: str,
12
context: dict[str, Any], doctree: Node) -> None:
13
"""
14
Register a function as a Jinja2 filter and fix canonical URLs.
15
16
Handles the html-page-context event to:
17
- Fix canonical URL generation for dirhtml builder
18
- Register custom template functions
19
- Enhance template context with theme-specific data
20
21
Parameters:
22
- app (Sphinx): The Sphinx application instance
23
- pagename (str): Current page name being rendered
24
- templatename (str): Name of the template being used
25
- context (dict[str, Any]): Template context dictionary
26
- doctree (Node): Document tree node for the page
27
"""
28
```
29
30
### Canonical URL Generation
31
32
Internal function that creates proper canonical URLs for directory-based builders.
33
34
```python { .api }
35
def _make_canonical(app: Sphinx, pagename: str) -> str:
36
"""
37
Turn a filepath into the correct canonical link.
38
39
Fixes canonical URL generation for the dirhtml builder, which
40
upstream Sphinx builds incorrectly. Ensures proper SEO and
41
URL structure for directory-based site organization.
42
43
Parameters:
44
- app (Sphinx): The Sphinx application instance
45
- pagename (str): Page name to convert to canonical URL
46
47
Returns:
48
str: Properly formatted canonical URL with trailing slash
49
"""
50
```
51
52
## URL Generation Issues
53
54
### Directory Builder Problem
55
56
The Sphinx `dirhtml` builder generates URLs like `/page/` instead of `/page.html`, but the canonical URL generation doesn't account for this properly. The template functions fix this issue.
57
58
### Before Fix (Incorrect)
59
60
```python
61
# Sphinx generates incorrect canonical URLs for dirhtml builder
62
canonical = "https://example.com/docs/installation.html" # Wrong for dirhtml
63
```
64
65
### After Fix (Correct)
66
67
```python
68
# Template function generates correct canonical URLs
69
canonical = "https://example.com/docs/installation/" # Correct for dirhtml
70
```
71
72
## Template Context Enhancements
73
74
The template functions enhance the Jinja2 context with corrected values:
75
76
### Page URL Override
77
78
```python
79
# For dirhtml builder with html_baseurl configured
80
if app.builder.name == "dirhtml" and app.config.html_baseurl:
81
context["pageurl"] = _make_canonical(app, pagename)
82
```
83
84
This ensures templates have access to properly formatted page URLs for:
85
- Canonical link tags
86
- Social media meta tags
87
- Sitemap generation
88
- Cross-page navigation
89
90
## Usage in Templates
91
92
### Canonical Link Generation
93
94
```html
95
<!-- In base template -->
96
{% if pageurl %}
97
<link rel="canonical" href="{{ pageurl }}">
98
{% endif %}
99
```
100
101
### Social Media Meta Tags
102
103
```html
104
<!-- Open Graph tags -->
105
<meta property="og:url" content="{{ pageurl }}">
106
<meta property="og:type" content="website">
107
108
<!-- Twitter Card tags -->
109
<meta name="twitter:url" content="{{ pageurl }}">
110
```
111
112
### Structured Data
113
114
```html
115
<!-- JSON-LD structured data -->
116
<script type="application/ld+json">
117
{
118
"@context": "https://schema.org",
119
"@type": "WebPage",
120
"url": "{{ pageurl }}",
121
"name": "{{ title }}"
122
}
123
</script>
124
```
125
126
## Builder Compatibility
127
128
### HTML Builder
129
130
Standard HTML builder generates files like `page.html`:
131
- No special URL handling needed
132
- Standard Sphinx canonical generation works correctly
133
134
### Directory HTML Builder
135
136
Directory HTML builder generates directory structure:
137
- Files saved as `page/index.html`
138
- URLs accessed as `/page/`
139
- Requires custom canonical URL generation
140
141
### Configuration Example
142
143
```python
144
# In conf.py
145
html_baseurl = "https://example.com/docs/"
146
147
# For dirhtml builder
148
extensions = [
149
# ... other extensions
150
]
151
152
# The template functions automatically detect dirhtml builder
153
# and fix canonical URLs when html_baseurl is configured
154
```
155
156
## SEO Benefits
157
158
### Proper Canonical URLs
159
160
Correct canonical URLs help search engines:
161
- Understand the preferred URL structure
162
- Avoid duplicate content penalties
163
- Index pages with consistent URL patterns
164
165
### URL Structure Consistency
166
167
Consistent URL patterns improve:
168
- User experience with predictable URLs
169
- Link sharing and bookmarking
170
- Site navigation and hierarchy understanding
171
172
## Event Integration
173
174
The template functions integrate with Sphinx's event system:
175
176
```python
177
# In theme setup
178
app.connect("html-page-context", setup_jinja)
179
```
180
181
This ensures the functions run for every page during the build process, providing consistent URL handling across the entire site.
182
183
## Error Handling
184
185
The template functions include robust error handling:
186
187
```python
188
# Safe canonical URL generation
189
if app.builder.name == "dirhtml" and app.config.html_baseurl:
190
# Only modify context if conditions are met
191
context["pageurl"] = _make_canonical(app, pagename)
192
```
193
194
This prevents issues when:
195
- `html_baseurl` is not configured
196
- Different builders are used
197
- Template context is missing expected values