Skip to content

Commit ebd2fb1

Browse files
Implement simple custom tag function
1 parent 5797975 commit ebd2fb1

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

pyhtml/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,12 +294,15 @@
294294
"""
295295
# Disable Flake8, since it really doesn't like our docstring above
296296
# flake8: noqa
297-
from .__tag_base import Tag
297+
from .__tag_base import Tag, create_tag, SelfClosingTag, WhitespaceSensitiveTag
298298

299299
from .__tags import input_, object_
300300

301301
__all__ = [
302302
'Tag',
303+
'create_tag',
304+
'SelfClosingTag',
305+
'WhitespaceSensitiveTag',
303306
'DangerousRawHtml',
304307
'Comment',
305308
'input_',

pyhtml/__tag_base.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,37 @@ def _render(self, indent: int) -> list[str]:
215215

216216
output += f"</{self._get_tag_name()}>"
217217
return output.splitlines()
218+
219+
220+
def create_tag(name: str, base: type[Tag] = Tag) -> type[Tag]:
221+
"""
222+
Create a new PyHTML tag definition.
223+
224+
PyHTML already provides definitions for all standard HTML tags, so you
225+
don't need to use this unless you are using a JavaScript library that
226+
defines custom HTML elements.
227+
228+
Args:
229+
name (str): the name of the tag. This is used during rendering, as
230+
`<{name}> ... </{name}>`.
231+
232+
base (type[Tag]): the base class to use for the custom tag. The new tag
233+
will inherit from this base class.
234+
235+
Returns:
236+
type[Tag]: a new tag definition.
237+
"""
238+
239+
def _get_tag_name(self) -> str:
240+
return name
241+
242+
# Generate custom type inheriting from given base class
243+
CustomTag = type(
244+
name,
245+
(base,),
246+
{
247+
'_get_tag_name': _get_tag_name,
248+
},
249+
)
250+
251+
return CustomTag

tests/custom_tag_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
# tests / custom tag test
3+
4+
Test cases for generating custom tags.
5+
"""
6+
import pyhtml as p
7+
8+
9+
def test_generate_custom_tag():
10+
t = p.create_tag('t')
11+
12+
assert str(t()) == '<t></t>'
13+
14+
15+
def test_base_class_set():
16+
t = p.create_tag('t', p.WhitespaceSensitiveTag)
17+
18+
assert issubclass(t, p.WhitespaceSensitiveTag)

0 commit comments

Comments
 (0)