Live templates in pure python with Hypergen
Rune Kaagaard & Jeppe Tuxen
def my_template():
section(
div(
"All html tags can be rendered using python ",
"functions with the same name",
span("Inside a span tag",
class_="my-class")
)
)
<section>
<div>
All html tags can be rendered using simple python
functions with the same name,
<span class="my-class">Inside a span tag</span>
</div>
</section>
p("One", " two", 3, title="Read me!")
<p title="Read me!">One two3</p>
p([1, 2, 3], (x for x in range(4,6)))
<p>123456</p>
p("Hi", id=["foo", 42],
class_={"class1", "class2"},
style=dict(background_color="green"))
<p class="class2 class1"
style="background-color:green" id="foo-42">Hi</p>
p("Hello", "world", sep=" ", end="!")
<p>Hello world!</p>
def yes_or_no_component(is_active):
span("YES" if is_active else "NO")
def row_component(instance):
# We can use tag functions as context managers
with tr(class_="green" if instance.is_active else ""):
td(instance.id)
td(instance.name)
td(
yes_or_no_component(instance.is_active)
)
def _table():
with table():
tr(
th("ID"),
th("Name"),
th("Active")
)
for instance in SomeDjangoModel.objects.all():
# Using the previously defined component
row_component(instance)