### htpy Element Creation Example Source: https://github.com/pelme/htpy/blob/main/docs/faq.md Illustrates the creation of Element instances for any elements that are imported. This is achieved through the module-level __getattr__ mechanism. ```python from htpy import Element # Example of creating an Element instance for a custom or non-standard tag custom_element = Element("my-custom-tag", "content") print(custom_element) ``` -------------------------------- ### Install htpy using pip Source: https://github.com/pelme/htpy/blob/main/docs/README.md Install the latest version of the htpy library using pip. This command should be run in your terminal or command prompt. ```bash pip install htpy ``` -------------------------------- ### Htpy Context Example Source: https://github.com/pelme/htpy/blob/main/docs/usage.md This Python snippet demonstrates passing data using Htpy's Context. It shows how to create a context, provide a value to a subtree, and consume that value in a child component using a decorator. The example uses a Theme literal for type safety. ```Python from typing import Literal from htpy import Context, Node, div, h1 Theme = Literal["light", "dark"] theme_context: Context[Theme] = Context("theme", default="light") def my_page() -> Node: return theme_context.provider( "dark", div[ h1["Hello!"], sidebar("The Sidebar!"), ], ) @theme_context.consumer def sidebar(theme: Theme, title: str) -> Node: return div(class_=f"theme-{theme}")[title] print(my_page()) ``` -------------------------------- ### Implement Custom Django Form Widget with htpy Source: https://github.com/pelme/htpy/blob/main/docs/how-to/django.md Create a custom Django form widget using htpy by subclassing `django.forms.widgets.Widget`. This example uses Shoelace's `` component. ```python from django.forms import widgets from htpy import sl_input class ShoelaceInput(widgets.Widget): """ A form widget using Shoelace's element. More info: https://shoelace.style/components/input """ def render(self, name, value, attrs=None, renderer=None): return str(sl_input(attrs, name=name, value=value)) ``` -------------------------------- ### Render Async Content with aiter_chunks() Source: https://github.com/pelme/htpy/blob/main/docs/how-to/async.md Use the `aiter_chunks()` method to get an async iterator yielding HTML document chunks as bytes. This is essential for streaming responses in web frameworks. Requires `asyncio` for execution. ```python import asyncio from htpy import p my_paragraph = p["hello!"] async def main() -> None: async for chunk in my_paragraph.aiter_chunks(): print(chunk) asyncio.run(main()) ``` -------------------------------- ### Stream Chunks without Parents using Fragment Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Wrap elements in `fragment` to get their chunks without rendering parent tags. Useful for partial rendering. ```python >>> from htpy import li, fragment >>> for chunk in fragment[li["a"], li["b"]].iter_chunks(): ... print(f"got a chunk: {chunk!r}") ... got a chunk: '
  • ' got a chunk: 'a' got a chunk: '
  • ' got a chunk: '
  • ' got a chunk: 'b' got a chunk: '
  • ' ``` -------------------------------- ### Integrate htpy into Django Templates Source: https://github.com/pelme/htpy/blob/main/docs/how-to/django.md Inject htpy-generated content into existing Django templates. htpy elements are marked as safe for direct rendering. This example shows injecting 'content' from a view into a base template. ```html My Django Site {{ content }} ``` ```python from django.shortcuts import render from htpy import h1 def index(request): return render(request, "base.html", { "content": h1["Welcome to my site!"], }) ``` -------------------------------- ### Basic Element Creation and Rendering Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Demonstrates creating a simple div element with an ID attribute and text content, then printing its HTML representation. ```pycon >>> from htpy import div >>> print(div(id="hi")["Hello!"])
    Hello!
    ``` -------------------------------- ### Creating a Flexible Bootstrap Alert Component Source: https://github.com/pelme/htpy/blob/main/docs/static-typing.md Demonstrates creating a wrapper component that accepts `Node` as input, allowing for flexible content types like strings or other elements. The function returns `Renderable` for general use. ```python from htpy import Node, Renderable, div def bootstrap_alert(contents: Node) -> Renderable: return div(".alert", role="alert")[contents] ``` -------------------------------- ### html2htpy CLI Usage Source: https://github.com/pelme/htpy/blob/main/docs/reference/html2htpy.md Displays the help message and available options for the html2htpy command. ```bash usage: html2htpy [-h] [-f {auto,ruff,black,none}] [-i {yes,h,no}] [--no-shorthand] [input] positional arguments: input Input HTML file, e.g. home.html. Optional. If not specified, html2htpy will read from stdin. options: -h, --help show this help message and exit -f, --format {auto,ruff,black,none} Format the output code with a code formatter. auto (default): - If black is installed (exists on PATH), use `black` for formatting. - If ruff is installed (exists on PATH): Use `ruff format` for formatting. - If neither black or ruff is installed, do not perform any formatting. black: Use the black formatter (https://black.readthedocs.io/en/stable/). ruff: Use the ruff formatter (https://docs.astral.sh/ruff/formatter/). none: Do not format the output code at all. -i, --imports {yes,h,no} Specify formatting for imports. yes (default): Add `from htpy import div, span` for all found elements. h: Add a single `import htpy as h`. Reference elements with `h.div`, `h.span`. no: Do not add imports. --no-shorthand Use explicit `id` and `class_` kwargs instead of the shorthand #id.class syntax. ``` -------------------------------- ### Using Fragments for Unwrapped Content Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Illustrates how to use the `fragment` helper to group multiple children that should be rendered without a parent element. ```pycon >>> from htpy import p, i, fragment >>> content = fragment["Hello ", None, i["world!"]] >>> print(content) Hello world! >>> print(p[content])

    Hello world!

    ``` -------------------------------- ### Use Bootstrap Modal Wrapper Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md Demonstrates how to use the `bootstrap_modal` function to render a modal with a title, body, and footer containing buttons. ```python from htpy import button, p print( bootstrap_modal( title="Modal title", body=p["Modal body text goes here."], footer=[ button(".btn.btn-primary", type="button")["Save changes"], button(".btn.btn-secondary", type="button")["Close"], ], ) ) ``` -------------------------------- ### Conditional Rendering with Boolean Variables Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Demonstrates conditional rendering using boolean variables and Python's 'and' and 'or' operators for inline logic. ```pycon >>> from htpy import div >>> is_happy = True >>> print(div[is_happy and "😄"])
    😄
    >>> is_sad = False >>> print(div[is_sad and "😔"])
    >>> is_allowed = True >>> print(div[is_allowed or "Access denied!"])
    >>> is_allowed = False >>> print(div[is_allowed or "Access denied!"])
    Access denied!
    ``` -------------------------------- ### Component with Children and Context Consumer Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md Shows how to combine the `@with_children` decorator with a context consumer decorator. The order of decorators and arguments is crucial for correct mapping. ```python from typing import Literal from htpy import Context, Node, Renderable, div, h1, with_children Theme = Literal["light", "dark"] theme_context: Context[Theme] = Context("theme", default="light") @with_children @theme_context.consumer def my_component(theme: Theme, children: Node, *, extra: str) -> Renderable: # Component implementation using theme and children pass ``` -------------------------------- ### Rendering a List of Child Elements Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Demonstrates rendering multiple child elements by passing a list of elements to the parent. This is useful for content that needs to be rendered multiple times. ```pycon >>> from htpy import div, img >>> my_images = [img(src="a.jpg"), img(src="b.jpg")] >>> print(div[my_images])
    ``` -------------------------------- ### Using a String as Children Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Illustrates rendering a heading element with a simple string as its child content. ```pycon >>> from htpy import h1 >>> print(h1["Welcome to my site!"])

    Welcome to my site!

    ``` -------------------------------- ### Id and Class Shorthand Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Use CSS selector-like syntax to quickly define `id` and `class` attributes for elements. ```pycon >>> from htpy import div >>> print(div("#myid"))
    ``` ```pycon >>> from htpy import div >>> print(div(".foo.bar"))
    ``` ```pycon >>> from htpy import div >>> print(div("#myid.foo.bar"))
    ``` -------------------------------- ### Rendering a Reusable Component Source: https://github.com/pelme/htpy/blob/main/docs/static-typing.md Shows how a component designed to return `Renderable` can be printed directly to produce an HTML string. This pattern is useful for standalone components or embedding in templates. ```python >>> from htpy import div, h1, Renderable >>> def my_component(name: str) -> Renderable: ... return div[h1[f"Hello {name}!"]] >>> print(my_component("Dave"))

    Hello Dave!

    ``` -------------------------------- ### Convert HTML snippets from clipboard to htpy Source: https://github.com/pelme/htpy/blob/main/docs/how-to/convert-html.md Pipe HTML content from the clipboard to the `html2htpy` command to convert it to htpy code. The output can be redirected to a file. ```bash xclip -o -selection clipboard | html2htpy > output.py ``` ```bash pbpaste | html2htpy > output.py ``` ```powershell powershell Get-Clipboard | html2htpy > output.py ``` -------------------------------- ### Specify Attributes via Multiple Arguments Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Combine shorthand selectors, keyword arguments, and dictionaries to specify attributes. ```python >>> from htpy import label >>> print(label("#myid.foo.bar", {'for': "somefield"}, name="myname",)) ``` -------------------------------- ### Module Import with htpy as h Source: https://github.com/pelme/htpy/blob/main/docs/reference/html2htpy.md Converts HTML to htpy Python code using `import htpy as h` for element referencing. ```python import htpy as h h.section("#main-section.hero.is-link")[ h.p(".subtitle.is-3.is-spaced")["Welcome"] ] ``` -------------------------------- ### Iterating Over a Generator for Children Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Shows how to generate multiple child elements by iterating over a generator expression, suitable for dynamic content. ```pycon >>> from htpy import ul, li >>> print(ul[(li[letter] for letter in "abc")]) ``` -------------------------------- ### Define Async Components in htpy Source: https://github.com/pelme/htpy/blob/main/docs/how-to/async.md Define components as `async def` functions. htpy will await these components during rendering. Ensure necessary imports like `htpy.li` and `asyncio` are included. ```python from htpy import li import asyncio async def get_text() -> str: return "hi!" async def my_text() -> Renderable: results = await get_text() return p[results] ``` -------------------------------- ### Defining a Bootstrap Badge Component Source: https://github.com/pelme/htpy/blob/main/docs/static-typing.md Illustrates creating a reusable `Element` component for a styled bootstrap badge. Use `Element` as the return type when the component is guaranteed to render an HTML element. ```python from typing import Literal from htpy import Element, span def bootstrap_badge( text: str, style: Literal["primary", "success", "danger"] = "primary", ) -> Element: return span(f".badge.text-bg-{style}")[text] ``` -------------------------------- ### Convert Component to Accept Children Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md Illustrates how to use the `@with_children` decorator to transform a component function into one that accepts children nodes directly, similar to HTML elements. ```python from htpy import Node, Renderable, with_children @with_children def my_component(children: Node, *, title: str) -> Renderable: # Component implementation that uses children pass ``` -------------------------------- ### Configure VS Code for Tailwind IntelliSense in htpy Source: https://github.com/pelme/htpy/blob/main/docs/tailwind.md Add this JSON configuration to your VS Code `settings.json` file to enable Tailwind CSS IntelliSense for htpy projects. This allows for autocompletion and hover information for Tailwind classes. ```json { "tailwindCSS.includeLanguages": { "python": "html" }, "tailwindCSS.experimental.classRegex": [ // keyword‑args and helper args: class_, base_classes, error_classes, etc. "\\b\\w*class\\w*\\b\\s*=\\s*['\\\"]([^'\\\"]*)['\\\"]", // dict‑style class entries: "class": "..." "['\\\"]class['\\\"]\\s*:\s*['\\\"]([^'\\\"]*)['\\\"]" ], ] } ``` -------------------------------- ### Convert HTML with Shorthand ID/Classes Source: https://github.com/pelme/htpy/blob/main/docs/reference/html2htpy.md Converts an HTML section to htpy Python code using shorthand notation for IDs and classes. ```python from htpy import p, section section("#main-section.hero.is-link")[ p(".subtitle.is-3.is-spaced")["Welcome"] ] ``` -------------------------------- ### Use htpy Components as Django Template Backend Source: https://github.com/pelme/htpy/blob/main/docs/how-to/django.md Configure Django to use htpy components as templates by adding `htpy.django.HtpyTemplateBackend` to `TEMPLATES`. This allows specifying htpy component functions as template names. ```python TEMPLATES = [ ... # Regular Django template configuration goes here {"BACKEND": "htpy.django.HtpyTemplateBackend", "NAME": "htpy"} ] ``` ```python from django.views.generic import ListView from pizza.models import Pizza class PizzaListView(ListView): model = Pizza template_name = "pizza.components.pizza_list" ``` ```python from htpy import li, ul def pizza_list(context, request): return ul[(li[pizza.name] for pizza in context["object_list"])])] ``` -------------------------------- ### Conditional Rendering with None Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Shows how to conditionally render an element based on a variable that might be None. If the variable is None, the element is not rendered. ```pycon >>> from htpy import div, b >>> error = None >>> # No tag will be rendered since error is None >>> print(div[error and b[error]])
    >>> error = 'Enter a valid email address.' >>> print(div[error and b[error]])
    Enter a valid email address.
    # Inline if/else can also be used: >>> print(div[b[error] if error else None])
    Enter a valid email address.
    ``` -------------------------------- ### Convert an HTML file to htpy code Source: https://github.com/pelme/htpy/blob/main/docs/how-to/convert-html.md Use the `html2htpy` command-line utility to convert an entire HTML file into its htpy Python equivalent. This is useful for migrating existing HTML projects. ```html htpy Recipes

    Recipe of the Day: Spaghetti Carbonara

    This classic Italian dish is quick and easy to make.

    ``` ```bash $ html2htpy index.html ``` ```python from htpy import body, div, h1, h2, head, html, meta, p, span, title html(lang="en")[ head[ meta(charset="UTF-8"), meta(name="viewport", content="width=device-width, initial-scale=1.0"), title["htpy Recipes"], ], body[ div("#header")[ h1["Welcome to the cooking site"], p["Your go-to place for delicious recipes!"] ], div("#recipe-of-the-day.section")[ h2["Recipe of the Day: ", span(".highlight")["Spaghetti Carbonara"]], p["This classic Italian dish is quick and easy to make."], ], div("#footer")[p["© 2024 My Cooking Site. All rights reserved."]], ], ] ``` -------------------------------- ### Nested Elements Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Shows how to create deeply nested HTML structures using htpy, combining articles, sections, and paragraphs. ```pycon >>> from htpy import article, section, p >>> print(section[article[p["Lorem ipsum"]]])

    Lorem ipsum

    ``` -------------------------------- ### Specifying Attributes as a Dictionary Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Attributes can be provided as a dictionary, which is useful for reserved keywords, attributes with dashes, or dynamic attribute definition. Multiple dictionaries can be combined. ```pycon >>> from htpy import button >>> print(button({"@click.shift": "addToSelection()"})) ``` ```pycon >>> from htpy import label >>> print(label({"for": "myfield"})) ``` ```pycon >>> from htpy import button >>> print(button({"disabled": True}, {"hx-post": "/foo"})) ``` -------------------------------- ### htpy Benchmark Script Source: https://github.com/pelme/htpy/blob/main/docs/faq.md A script to benchmark htpy's performance by generating a large HTML table. This can be used to compare rendering speeds with other template engines. ```python from htpy import Table, Tr, Td def benchmark_big_table(): rows = 50000 cols = 10 table = Table() for _ in range(rows): row = Tr() for _ in range(cols): row.add(Td("cell")) table.add(row) return table if __name__ == "__main__": import time start = time.time() benchmark_big_table() end = time.time() print(f"Generated table in {end - start:.4f} seconds") ``` -------------------------------- ### htpy Element Creation via Module Attribute Access Source: https://github.com/pelme/htpy/blob/main/docs/faq.md Demonstrates how htpy utilizes Python's module-level __getattr__ to dynamically create Element instances for any imported tag name. This feature was introduced in Python 3.7. ```python from htpy import * # noqa # This works because __getattr__ is defined at the module level # and creates Element instances for any imported tag name. html = html_document(head=head(title("My Page")), body=body(h1("Hello, World!"))) print(html) ``` -------------------------------- ### Create Wrapper for Bootstrap Modal Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md Define a reusable function to generate Bootstrap Modal HTML structures. This function takes a title, body, and footer as arguments to construct the modal. ```python from markupsafe import Markup from htpy import Node, Renderable, button, div, h5, span def bootstrap_modal(*, title: str, body: Node = None, footer: Node = None) -> Renderable: return div(".modal", tabindex="-1", role="dialog")[ div(".modal-dialog", role="document")[ div(".modal-content")[ div(".modal-header")[ div(".modal-title")[ h5(".modal-title")[title], button( ".close", type="button", data_dismiss="modal", aria_label="Close", )[span(aria_hidden="true")[Markup("×")]], ] ], div(".modal-body")[body], footer and div(".modal-footer")[footer], ] ] ] ``` -------------------------------- ### Specifying Attributes via Keyword Arguments Source: https://github.com/pelme/htpy/blob/main/docs/usage.md HTML attributes can be set using keyword arguments. For Python reserved keywords like `class` and `for`, use `class_` and `for_` respectively. ```pycon >>> from htpy import img >>> print(img(src="picture.jpg")) ``` ```pycon >>> from htpy import label >>> print(label(for_="myfield")) ``` ```pycon >>> from htpy import form >>> print(form(hx_post="/foo"))
    ``` -------------------------------- ### Conditionally Mix CSS Classes Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Use a list of class names or a dictionary for the 'class_' attribute. Falsey values are ignored. ```python >>> from htpy import button >>> is_primary = True >>> print(button(class_=['btn', {'btn-primary': is_primary}])) >>> is_primary = False >>> print(button(class_=['btn', {'btn-primary': is_primary}])) >>> ``` -------------------------------- ### Injecting Markup Safely Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Use `Markup` from the `markupsafe` library to insert raw HTML markup without escaping. `markupsafe` is a dependency of htpy. ```pycon >>> from htpy import div >>> from markupsafe import Markup >>> print(div[Markup("")])
    ``` -------------------------------- ### Convert Jinja templates with loops to htpy Source: https://github.com/pelme/htpy/blob/main/docs/how-to/convert-html.md While `html2htpy` converts simple template variables, complex syntax like Jinja loops (`{% for %}`) are partially converted and may require manual cleanup. The loop structure itself is preserved as a string. ```html

    {{ heading }}

    Welcome to our cooking site, {{ user.name }}!

    Recipe of the Day: {{ recipe.name }}

    {{ recipe.description }}

    Instructions:

      {% for step in recipe.steps %}
    1. {{ step }}
    2. {% endfor %}
    ``` ```python from htpy import body, h1, h2, h3, li, ol, p body[ h1[f"{ heading }"], p[f"Welcome to our cooking site, { user.name }!"], h2[f"Recipe of the Day: { recipe.name }"], p[f"{ recipe.description }"], h3["Instructions:"], ol[" {% for step in recipe.steps %}", li[f"{ step }"], " {% endfor %}"], ] ``` -------------------------------- ### Return htpy Content from a Starlette Handler Source: https://github.com/pelme/htpy/blob/main/docs/how-to/starlette.md Use HtpyResponse to return rendered htpy components from a Starlette request handler. Ensure the component function is async. ```python from starlette.applications import Starlette from starlette.requests import Request from starlette.routing import Route from htpy import Element, h1 from htpy.starlette import HtpyResponse async def index_component() -> Element: return h1["Hi Starlette!"] async def index(request: Request) -> HtpyResponse: return HtpyResponse(index_component()) app = Starlette( routes=[ Route("/", index), ] ) ``` -------------------------------- ### Base Layout Component for htpy Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md Defines a reusable base layout for HTML pages, including head, body, and footer sections. It accepts parameters for page title, extra head content, body class, and main content. ```python import datetime from htpy import Node, Renderable, body, div, h1, head, html, p, title def base_layout(*, page_title: str | None = None, extra_head: Node = None, content: Node = None, body_class: str | None = None, ) -> Renderable: return html[ head[title[page_title], extra_head], body(class_=body_class)[ content, div("#footer")[f"Copyright {datetime.date.today().year} by Foo Inc."], ], ] def index_page() -> Renderable: return base_layout( page_title="Welcome!", body_class="green", content=[ h1["Welcome to my site!"], p["Hello and welcome!"], ], ) def about_page() -> Renderable: return base_layout( page_title="About us", content=[ h1["About us"], p["We love creating web sites!"], ], ) ``` -------------------------------- ### htpy Greeting Component Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md A simple htpy component function that generates an HTML structure with a personalized greeting. It uses keyword-only arguments for clarity. ```python from htpy import Renderable, body, html, h1 def greeting_page(*, name: str) -> Renderable: return html[body[h1[f"hi {name}!"]]] ``` -------------------------------- ### Using Custom Elements with Underscores Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Explains how to use custom HTML elements (web components) in htpy by replacing hyphens with underscores in their names. ```pycon >>> from htpy import my_custom_element >>> print(my_custom_element['hi!']) hi! ``` -------------------------------- ### Define HTML in Python Source: https://github.com/pelme/htpy/blob/main/docs/README.md This snippet demonstrates how to define an HTML structure, including a title, heading, and an unordered list with items, using htpy's Pythonic syntax. It requires importing necessary HTML tag functions from the htpy library. ```python from htpy import body, h1, head, html, li, title, ul menu = ["egg+bacon", "bacon+spam", "eggs+spam"] print( html[ head[title["Today's menu"]], body[ h1["Menu"], ul(".menu")[(li[item] for item in menu)], ], ] ) ``` -------------------------------- ### Convert HTML with Django/Jinja Variables Source: https://github.com/pelme/htpy/blob/main/docs/reference/html2htpy.md Converts HTML containing Django/Jinja variables into htpy Python code with f-string interpolation. ```python from htpy import div div[f"hi { name }!"] ``` -------------------------------- ### Catching Attribute Errors with Mypy Source: https://github.com/pelme/htpy/blob/main/docs/static-typing.md Demonstrates how mypy detects attribute errors in htpy components by analyzing type annotations. Ensure your component logic aligns with defined types. ```python class User: def __init__(self, name: str): self.name = name def greeting(user: User) -> Renderable: return h1[f"Hi {user.first_name.capitalize()}!"] # ^^^^^^^^^^^ # mypy: error: "User" has no attribute "first_name" [attr-defined] ``` -------------------------------- ### Django View Using htpy Component Source: https://github.com/pelme/htpy/blob/main/docs/common-patterns.md This snippet shows how a Django view function can render HTML generated by an htpy component. It demonstrates passing dynamic data to the component. ```python from django.http import HttpRequest, HttpResponse from .components import greeting_page def greeting(request: HttpRequest) -> HttpResponse: return HttpResponse(greeting_page( name=request.GET.get("name", "anonymous"), )) ``` -------------------------------- ### Stream HTML Chunks Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Use `iter_chunks()` to render an element and its children piece by piece. This is useful for streaming large HTML structures. ```python >>> from htpy import ul, li >>> for chunk in ul[li["a"], li["b"]].iter_chunks(): ... print(f"got a chunk: {chunk!r}") ... got a chunk: '
      ' got a chunk: '
    • ' got a chunk: 'a' got a chunk: '
    • ' got a chunk: '
    • ' got a chunk: 'b' got a chunk: '
    • ' got a chunk: '
    ' ``` -------------------------------- ### Rendering Elements Without Attributes Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Elements that do not support attributes can be rendered by simply using the element function. ```pycon >>> from htpy import hr >>> print(hr)
    ``` -------------------------------- ### Convert HTML with Explicit ID/Class Attributes Source: https://github.com/pelme/htpy/blob/main/docs/reference/html2htpy.md Converts an HTML section to htpy Python code using explicit `id` and `class_` attributes via the `--no-shorthand` flag. ```python from htpy import p, section section(id="main-section", class_="hero is-link")[ p(class_="subtitle is-3 is-spaced")["Welcome"] ] ``` -------------------------------- ### Injecting Generated Markdown Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Mark generated Markdown as safe using `Markup` before inserting it into an htpy element. ```pycon >>> from markdown import markdown >>> from markupsafe import Markup >>> from htpy import div >>> print(div[Markup(markdown('# Hi'))])

    Hi

    ``` -------------------------------- ### Return htpy Response from Django View Source: https://github.com/pelme/htpy/blob/main/docs/how-to/django.md Render a htpy HTML structure directly within a Django HttpResponse. Ensure `htpy.html`, `htpy.body`, and `htpy.div` are imported. ```python from django.http import HttpResponse from htpy import html, body, div def my_view(request): return HttpResponse(html[body[div["Hi Django!"]]]) ``` -------------------------------- ### Handle Async Rendering Errors Source: https://github.com/pelme/htpy/blob/main/docs/how-to/async.md Avoid calling `str()` on async renderables. Instead, use `aiter_chunks()` to iterate over the content. Attempting to stringify an async component directly will raise a `TypeError`. ```python async for chunk in div[my_async_component()].aiter_chunks(): print(chunk) ``` -------------------------------- ### Convert Django/Jinja template variables to f-strings Source: https://github.com/pelme/htpy/blob/main/docs/how-to/convert-html.md The `html2htpy` utility converts Django/Jinja template variables within HTML to Python f-strings. This simplifies the migration of dynamic content. ```html
    hi {{ name }}!
    ``` ```python from htpy import div div[f"hi { name }!"] ``` -------------------------------- ### Boolean and Empty Attributes Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Set boolean attributes like `disabled` by assigning `True` or `False`. `True` renders the attribute without a value, while `False` hides it. ```pycon >>> from htpy import button >>> print(button(disabled=True)) ``` ```pycon >>> from htpy import button >>> print(button(disabled=False)) ``` -------------------------------- ### Generating HTML Comments Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Use the `comment` function to emit HTML comments visible in the browser. Double dashes (`--`) are removed to prevent breaking out of comments. ```pycon >>> from htpy import div, comment >>> print(div[comment("This is a HTML comment, visible in the browser!")])
    ``` -------------------------------- ### Safe String Escaping with f-strings Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Demonstrates how htpy automatically escapes strings to prevent XSS vulnerabilities, even when using f-strings with potentially unsafe input. ```pycon >>> from htpy import h1 >>> user_supplied_name = "bobby " >>> print(h1[f"hello {user_supplied_name}"])

    hello bobby </h1>

    ``` -------------------------------- ### HTML Doctype Generation Source: https://github.com/pelme/htpy/blob/main/docs/usage.md The HTML doctype is automatically prepended to the `` tag when `html` is used. ```pycon >>> from htpy import html >>> print(html) ``` -------------------------------- ### Generated HTML Output Source: https://github.com/pelme/htpy/blob/main/docs/README.md This is the HTML output generated by the preceding Python code snippet. It represents a standard HTML document with a head section containing a title and a body section with a heading and an unordered list. ```html Today's menu

    Menu

    ``` -------------------------------- ### Consume Async Iterators in htpy Source: https://github.com/pelme/htpy/blob/main/docs/how-to/async.md htpy can consume async iterators. Define an async generator function that yields `Renderable` items, such as `li` elements, to be used within htpy components. ```python from htpy import ul, li async def my_items() -> AsyncIterator[Renderable]: yield li["a"] yield li["b"] def my_list() -> Renderable: return ul[my_items()] ``` -------------------------------- ### Delay Evaluation with Callables Source: https://github.com/pelme/htpy/blob/main/docs/streaming.md Pass a callable (like a function or lambda) as a child element to delay its evaluation until rendering. This is useful for computationally intensive tasks or operations with side effects. ```python import time from htpy import div, h1 def calculate_magic_number() -> str: time.sleep(1) print(" (running the complex calculation...)") return "42" element = div[ h1["Welcome to my page"], "The magic number is ", calculate_magic_number, ] for chunk in element: print(chunk) ``` ```python from htpy import div, h1 def fib(n: int) -> int: if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) print( div[ h1["Fibonacci!"], "fib(20)=", lambda: str(fib(20)), ] ) # output:

    Fibonacci!

    fib(20)=6765
    ``` -------------------------------- ### Stream Django Articles with Generators Source: https://github.com/pelme/htpy/blob/main/docs/streaming.md Use a generator expression with Django's lazily evaluated querysets to stream a list of articles. This avoids executing database queries until the content is needed for rendering. ```python from django.http import StreamingHttpResponse from htpy import ul, li from myapp.models import Article def article_list(request): return StreamingHttpResponse(ul[ (li[article.title] for article in Article.objects.all()) ]) ``` -------------------------------- ### Render Django Form with htpy Source: https://github.com/pelme/htpy/blob/main/docs/how-to/django.md Use htpy to render Django forms, including CSRF tokens, form errors, and widgets. The `csrf_input` function is used for security, and form fields are accessed via dictionary-like access. ```python from django import forms class MyForm(forms.Form): name = forms.CharField() ``` ```python from django.http import HttpRequest, HttpResponse from .components import my_form_page, my_form_success_page from .forms import MyForm def my_form(request: HttpRequest) -> HttpResponse: form = MyForm(request.POST or None) if form.is_valid(): return HttpResponse(my_form_success_page()) return HttpResponse(my_form_page(request, my_form=form)) ``` ```python from django.http import HttpRequest from django.template.backends.utils import csrf_input from htpy import Node, Renderable, body, button, form, h1, head, html, title from .forms import MyForm def base_page(page_title: str, content: Node) -> Renderable: return html[ head[title[page_title]], body[content], ] def my_form_page(request: HttpRequest, *, my_form: MyForm) -> Renderable: return base_page( "My form", form(method="post")[ csrf_input(request), my_form.errors, my_form["name"], button["Submit!"] ], ) def my_form_success_page() -> Renderable: return base_page( "Success!", h1["Success! The form was valid!"] ) ``` -------------------------------- ### Escape Markup in Attributes Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Escaping occurs even with markupsafe.Markup, which is useful for embedding HTML snippets as attributes. ```python >>> from htpy import ul >>> from markupsafe import Markup >>> # This markup may come from another library/template engine >>> some_markup = Markup("
  • ") >>> print(ul(data_li_template=some_markup))
      ``` -------------------------------- ### Escape HTML Attributes Source: https://github.com/pelme/htpy/blob/main/docs/usage.md Attributes are always escaped to safely include HTML fragments or scripts. The browser interprets escaped characters correctly. ```python >>> from htpy import button >>> print(button(onclick="let name = 'andreas'; alert('hi' + name);")["Say hi"]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.