0
# HTML Element Generation
1
2
Comprehensive HTML generation system based on Jinja2 templating for creating structured web content. Provides hierarchical element organization, template-based rendering, and specialized components for building complete HTML documents and interactive visualizations.
3
4
## Capabilities
5
6
### Core Element System
7
8
Base element class providing template rendering, child management, and hierarchical document structure.
9
10
```python { .api }
11
class Element:
12
def __init__(self, template=None, template_name=None):
13
"""
14
Create basic HTML element with optional template.
15
16
Parameters:
17
- template: Jinja2 template string for custom rendering
18
- template_name: filename of template from branca templates
19
"""
20
21
def get_name(self) -> str:
22
"""
23
Get unique string identifier for this element.
24
25
Returns:
26
str: unique element name (camelCase + ID)
27
"""
28
29
def add_child(self, child, name=None, index=None):
30
"""
31
Add child element to this element.
32
33
Parameters:
34
- child: Element instance to add as child
35
- name: optional name for the child (auto-generated if None)
36
- index: optional position index for insertion
37
38
Returns:
39
Element: self for method chaining
40
"""
41
42
def add_children(self, child, name=None, index=None):
43
"""
44
Add child element to this element (deprecated, use add_child instead).
45
46
Parameters:
47
- child: Element instance to add as child
48
- name: optional name for the child (auto-generated if None)
49
- index: optional position index for insertion
50
51
Returns:
52
Element: self for method chaining
53
"""
54
55
def add_to(self, parent, name=None, index=None):
56
"""
57
Add this element to a parent element.
58
59
Parameters:
60
- parent: Element instance to add this element to
61
- name: optional name for this element
62
- index: optional position index for insertion
63
64
Returns:
65
Element: self for method chaining
66
"""
67
68
def get_bounds(self) -> list:
69
"""
70
Get bounding box coordinates for this element and children.
71
72
Returns:
73
list: [[lat_min, lon_min], [lat_max, lon_max]] with Optional[float] values
74
"""
75
76
def get_root(self) -> "Element":
77
"""
78
Get root element in the element tree.
79
80
Returns:
81
Element: root element instance
82
"""
83
84
def render(self, **kwargs) -> str:
85
"""
86
Render element to HTML string using template.
87
88
Parameters:
89
- **kwargs: template variables for rendering
90
91
Returns:
92
str: rendered HTML content
93
"""
94
95
def save(self, outfile, close_file=True, **kwargs):
96
"""
97
Save rendered HTML to file.
98
99
Parameters:
100
- outfile: file path or file object
101
- close_file: whether to close file after writing
102
- **kwargs: template variables for rendering
103
"""
104
105
def to_dict(self, depth: int = -1, ordered: bool = True, **kwargs):
106
"""
107
Convert element tree to dictionary representation.
108
109
Parameters:
110
- depth: maximum depth for recursion (-1 for unlimited)
111
- ordered: whether to use OrderedDict
112
113
Returns:
114
dict | OrderedDict: dictionary representation of element tree
115
"""
116
117
def to_json(self, depth: int = -1, **kwargs) -> str:
118
"""
119
Convert element tree to JSON string.
120
121
Parameters:
122
- depth: maximum depth for recursion (-1 for unlimited)
123
- **kwargs: additional JSON serialization options
124
125
Returns:
126
str: JSON representation of element tree
127
"""
128
```
129
130
### Complete HTML Documents
131
132
Figure class for creating full HTML documents with separate header, body, and script sections.
133
134
```python { .api }
135
class Figure:
136
def __init__(
137
self,
138
width: str = "100%",
139
height=None,
140
ratio: str = "60%",
141
title=None,
142
figsize=None
143
):
144
"""
145
Create complete HTML document structure.
146
147
Parameters:
148
- width: document width (percentage or pixels)
149
- height: document height (percentage or pixels)
150
- ratio: aspect ratio when height is None
151
- title: HTML document title
152
- figsize: matplotlib-style (width, height) in inches (60 DPI)
153
"""
154
155
# Attributes
156
header: Element # HTML head section
157
html: Element # HTML body section
158
script: Element # JavaScript section
159
160
def render(self, **kwargs) -> str:
161
"""
162
Render complete HTML document.
163
164
Parameters:
165
- **kwargs: template variables
166
167
Returns:
168
str: complete HTML document string
169
"""
170
171
def _repr_html_(self, **kwargs) -> str:
172
"""
173
Jupyter notebook display representation.
174
175
Returns:
176
str: HTML iframe for notebook display
177
"""
178
179
def add_subplot(self, x: int, y: int, n: int, margin: float = 0.05):
180
"""
181
Create matplotlib-style subplot div.
182
183
Parameters:
184
- x: number of rows in grid
185
- y: number of columns in grid
186
- n: cell number (1 to x*y)
187
- margin: spacing factor around subplot
188
189
Returns:
190
Div: positioned div element for subplot
191
"""
192
```
193
194
### HTML Content Containers
195
196
Specialized elements for embedding HTML content with custom styling and positioning.
197
198
```python { .api }
199
class Html:
200
def __init__(
201
self,
202
data: str,
203
script: bool = False,
204
width = "100%",
205
height = "100%"
206
):
207
"""
208
Create HTML div element with embedded content.
209
210
Parameters:
211
- data: HTML content string
212
- script: if True, data is embedded without HTML escaping
213
- width: div width (percentage, pixels, or tuple)
214
- height: div height (percentage, pixels, or tuple)
215
"""
216
217
def render(self, **kwargs) -> str:
218
"""
219
Render HTML div with content.
220
221
Returns:
222
str: HTML div element with embedded content
223
"""
224
225
class Div:
226
def __init__(
227
self,
228
width = "100%",
229
height = "100%",
230
left = "0%",
231
top = "0%",
232
position: str = "relative"
233
):
234
"""
235
Create positioned div container for layout.
236
237
Parameters:
238
- width: div width (percentage, pixels, or tuple)
239
- height: div height (percentage, pixels, or tuple)
240
- left: left position offset
241
- top: top position offset
242
- position: CSS position property value
243
"""
244
245
# Attributes (inherited from Figure)
246
header: Element # CSS styles section
247
html: Element # Content section
248
script: Element # JavaScript section
249
250
def render(self, **kwargs):
251
"""
252
Render positioned div with styles in parent Figure.
253
Must be added to a Figure to render properly.
254
"""
255
```
256
257
### Embedded Content
258
259
IFrame element for embedding complete web pages with isolated JavaScript environments.
260
261
```python { .api }
262
class IFrame:
263
def __init__(
264
self,
265
html=None,
266
width: str = "100%",
267
height=None,
268
ratio: str = "60%",
269
figsize=None
270
):
271
"""
272
Create iframe element with base64-encoded content.
273
274
Parameters:
275
- html: HTML content string or Element instance
276
- width: iframe width (percentage or pixels)
277
- height: iframe height (percentage or pixels)
278
- ratio: aspect ratio when height is None
279
- figsize: matplotlib-style (width, height) in inches
280
"""
281
282
def render(self, **kwargs) -> str:
283
"""
284
Render iframe with base64-encoded content.
285
286
Returns:
287
str: HTML iframe element with data URL
288
"""
289
```
290
291
### External Resource Links
292
293
Elements for embedding JavaScript and CSS resources from URLs.
294
295
```python { .api }
296
class Link:
297
def __init__(self, url: str, download: bool = False):
298
"""
299
Base class for external resource links.
300
301
Parameters:
302
- url: resource URL
303
- download: whether to download content immediately
304
"""
305
306
def get_code(self) -> bytes:
307
"""
308
Download and return resource content.
309
310
Returns:
311
bytes: downloaded content
312
"""
313
314
class JavascriptLink(Link):
315
def __init__(self, url: str, download: bool = False):
316
"""
317
JavaScript link element for embedding JS files.
318
319
Parameters:
320
- url: JavaScript file URL
321
- download: whether to download content immediately
322
"""
323
324
class CssLink(Link):
325
def __init__(self, url: str, download: bool = False):
326
"""
327
CSS link element for embedding stylesheets.
328
329
Parameters:
330
- url: CSS file URL
331
- download: whether to download content immediately
332
"""
333
```
334
335
### Template-Based Components
336
337
MacroElement base class for creating complex components with multiple HTML sections.
338
339
```python { .api }
340
class MacroElement:
341
def __init__(self):
342
"""
343
Base class for elements using Jinja2 macro templates.
344
Subclasses should define _template with header, html, and script macros.
345
"""
346
347
def render(self, **kwargs):
348
"""
349
Process macro template and add sections to parent Figure.
350
Must be added to a Figure to render properly.
351
"""
352
```
353
354
## Usage Examples
355
356
### Creating Complete HTML Documents
357
358
```python
359
from branca.element import Figure, Html, JavascriptLink, CssLink
360
361
# Create basic HTML document
362
fig = Figure(width='800px', height='600px', title='My Page')
363
364
# Add CSS and JavaScript resources
365
fig.header.add_child(CssLink('https://cdn.example.com/styles.css'))
366
fig.header.add_child(JavascriptLink('https://cdn.example.com/script.js'))
367
368
# Add HTML content
369
content = Html('<h1>Welcome</h1><p>This is my page content.</p>', script=True)
370
fig.html.add_child(content)
371
372
# Add JavaScript code
373
fig.script.add_child(Html('console.log("Page loaded");', script=True))
374
375
# Save to file
376
fig.save('my_page.html')
377
```
378
379
### Creating Layouts with Positioned Divs
380
381
```python
382
from branca.element import Figure, Div, Html
383
384
fig = Figure(width='1000px', height='600px')
385
386
# Create header div
387
header = Div(width='100%', height='80px', top='0%', position='absolute')
388
header.html.add_child(Html('<h1>Page Header</h1>', script=True))
389
fig.add_child(header)
390
391
# Create sidebar div
392
sidebar = Div(width='200px', height='520px', left='0%', top='80px', position='absolute')
393
sidebar.html.add_child(Html('<nav>Navigation Menu</nav>', script=True))
394
fig.add_child(sidebar)
395
396
# Create main content div
397
main_content = Div(width='800px', height='520px', left='200px', top='80px', position='absolute')
398
main_content.html.add_child(Html('<main>Main Content Area</main>', script=True))
399
fig.add_child(main_content)
400
401
fig.save('layout.html')
402
```
403
404
### Creating Subplots
405
406
```python
407
from branca.element import Figure, Html
408
409
fig = Figure(figsize=(12, 8))
410
411
# Create 2x2 grid of subplots
412
for i in range(1, 5):
413
subplot = fig.add_subplot(2, 2, i, margin=0.05)
414
subplot.html.add_child(Html(f'<h3>Subplot {i}</h3>', script=True))
415
416
fig.save('subplots.html')
417
```
418
419
### Using IFrames for Isolated Content
420
421
```python
422
from branca.element import Figure, IFrame, Html
423
424
# Create iframe with isolated HTML content
425
iframe_content = '''
426
<html>
427
<head><title>Iframe Content</title></head>
428
<body>
429
<h2>This content is isolated</h2>
430
<script>console.log("Iframe script");</script>
431
</body>
432
</html>
433
'''
434
435
fig = Figure()
436
iframe = IFrame(iframe_content, width='600px', height='400px')
437
fig.html.add_child(iframe)
438
439
fig.save('iframe_example.html')
440
```
441
442
## Type Definitions
443
444
```python { .api }
445
# Size parsing type for width/height parameters
446
TypeParseSize = int | float | str | tuple[float, str]
447
```
448
449
## Global Objects
450
451
```python { .api }
452
# Jinja2 environment for branca templates
453
ENV: Environment
454
```