duck.html.components.page

Module Contents

Classes

ErrorPage

Basic error page with customizable status code and message.

EventHandlerChain

Class representing an event handler chain.

Page

Full-featured HTML page component with SEO, social, accessibility, i18n, performance, and analytics support.

API

class duck.html.components.page.ErrorPage(status_code: int, message: str, *args, **kwargs)[source]

Bases: duck.html.components.page.Page

Basic error page with customizable status code and message.

Initialization

Initialize the Page component.

Parameters:
  • request – The target HTTP request.

  • disable_lively – This disables Lively components for the page. Defaults to False.

  • lazy – This makes the page not aggressively load the page tree on initialization but let the system decide the right time to load the page. Defaults to True.

on_create()[source]
class duck.html.components.page.EventHandlerChain[source]

Class representing an event handler chain.

Initialization

__slots__

(‘_event_handlers’, ‘_execution_results’)

add_event_handler(event_handler: Callable, update_targets: Set[HtmlComponent])[source]

Adds new event handler to event handler chain.

all_update_targets() Set[HtmlComponent][source]

Returns all update targets for each and every event handler.

async async_execute(args: Union[Tuple, Iterable], restart: bool = False) Dict[Callable, Any][source]

Execute all event handlers and return results.

Parameters:
  • args – These are positional arguments to parse to event handlers.

  • restart – By default, if this method is called more than once, the actual event handler execution does not happen and cached results will be returned. This also mean if some some execution of an event handler fails after execution of other event handlers, those successful event handlers’ results will be cached. Set this to True to execute all event handlers.

exception duck.html.components.page.EventHandlerChainError[source]

Bases: duck.html.components.page.PageError

Raised on exceptions related to event handler chaining.

Initialization

Initialize self. See help(type(self)) for accurate signature.

class duck.html.components.page.Page(request, disable_lively: bool = False, lazy: bool = True, *args, **kwargs)[source]

Bases: duck.html.components.InnerComponent

Full-featured HTML page component with SEO, social, accessibility, i18n, performance, and analytics support.

Initialization

Initialize the Page component.

Parameters:
  • request – The target HTTP request.

  • disable_lively – This disables Lively components for the page. Defaults to False.

  • lazy – This makes the page not aggressively load the page tree on initialization but let the system decide the right time to load the page. Defaults to True.

add_child(child)[source]
add_google_analytics(tracking_id: str) List[duck.html.components.script.Script][source]

Add Google Analytics snippet with the given tracking ID.

Returns:

Script for the google tag manager and the other is the Google Analytics script.

Return type:

List[Script]

… admonition:: Notes

Make sure you include https://googletagmanager.com in CSP script-src if you are using Content Security Policy.

Example:

add_google_analytics("UA-XXXXX-Y")
add_meta(**kwargs) duck.html.components.NoInnerComponent[source]

Add meta tag to the page’s head.

Parameters:

**kwargs – Additional keyword arguments to pass to meta component.

Returns:

The generated meta component.

Return type:

NoInnerComponent

add_script(src: Optional[str] = None, inline: Optional[str] = None, async_: bool = False, defer: bool = False, **attrs) Optional[duck.html.components.script.Script][source]

Add a script tag.

Parameters:
  • src – External script URL.

  • inline – Inline JS code.

  • async_ – Async attribute.

  • defer – Defer attribute.

  • attrs – Other script attributes.

Returns:

The script component or None (if script source already exists), you can store this component to remove it later.

Return type:

Optional[Script]

add_stylesheet(href: str, add_to_noscript: bool = False, **attrs) Optional[duck.html.components.Component][source]

Add a stylesheet link.

Parameters:
  • href – URL of stylesheet.

  • add_to_noscript – Whether to add the stylesheet inside <noscript> tags.

  • **attrs – Additional attributes like media, integrity, crossorigin.

Returns:

The added component or None (if stylesheet source already exists), you can store this component to remove it later.

Return type:

Optional[Component]

Notes:

  • For the “as” property just parse it as as_ instead.

add_to_body(child_or_childs: Union[duck.html.components.Component, List[duck.html.components.Component]])[source]

Add component(s) to the body.

add_to_head(child_or_childs: Union[duck.html.components.Component, List[duck.html.components.Component]])[source]

Add component(s) to the head.

document_bind(event: str, event_handler: Callable, force_bind: bool = False, update_targets: List[HtmlComponent] = None, update_self: bool = True, event_handler_chaining: bool = False) None[source]

Bind an event handler to the document object.

Parameters:
  • event – The name of the event to bind (e.g., “DOMContentLoaded”, “DuckNavigated”).

  • event_handler – A callable (preferably async) that handles the event.

  • force_bind – If True, binds the event even if it’s not in the recognized set.

  • update_targets – Other components whose state may be modified when this event is triggered. Defaults to None.

  • update_self – Whether this component’s state may change as a result of the event. If False, only other components will be considered for DOM updates. Defaults to True.

  • event_handler_chaining – This force binding to event even if the event is already bound. This creates a chain of event handlers that will be executed in order when an event happens.

Raises:
  • UnknownEventError – If the event is not recognized and force_bind is False.

  • AssertionError – If the event handler is not a callable.

  • RedundantUpdate – If any component pair in update_targets share the same root/parent.

  • EventAlreadyBound – If event is already bound.

Notes:

  • If update_self is False and no update_targets are provided, no DOM patch will be sent to the client.

  • This method requires the Lively Component System to be active (i.e., running within a WebSocket context).

  • On navigating to a new page, the following events will be fired:

    • DOMContentLoaded

    • DuckNavigated You can bind listeners to these events to perform cleanup actions, such as closing open components (dropdowns, modals, etc.).

  • Unbinding document event handlers using document_unbind only works if no navigation occurs. If navigation does happen, the newly visited page will restart following the default flow it was created with, thus, rebinding event handlers (violating the document_unbind).

document_unbind(event: str, failsafe: bool = True)[source]

Remove/unbind an event from the document.

Parameters:
  • event – The event name to unbind.

  • failsafe – If True (default), silently ignore if the event was never bound. If False, raise UnknownEventError if the event does not exist.

Raises UnknownEventError: If failsafe is False and the event is not bound.

Notes:

  • Unbinding document event handlers using document_unbind only works if no navigation occurs. If navigation does happen, the newly visited page will restart following the default flow it was created with, thus, rebinding event handlers (violating the document_unbind).

get_document_event_info(event: str) Tuple[Callable, Set[HtmlComponent]][source]

Returns the event info in form: (event_handler, update_targets).

get_element() str[source]
get_request_or_raise() HttpRequest[source]

Retrieves a request object from component kwargs or raise an exception.

Raises:

RequestNotFoundError – If the request is not in kwargs or kwargs[‘context’] (if used in templates).

on_create()[source]
render()[source]
property request: HttpRequest

Returns the request object, raises if missing.

set_accessibility(lang: Optional[str] = None, role: Optional[str] = None)[source]

Setup accessibility related props on and .

Parameters:
  • lang – Set html lang attribute.

  • role – Set role attribute on body, e.g., ‘main’.

set_article_json_ld(headline: str, author_name: str, date_published: str, description: str, url: Optional[str] = None)[source]

Add Article JSON-LD structured data.

set_author(author: str)[source]

Set the author meta tag.

Parameters:

author – The author name - personal or organisation name.

set_canonical(url: str)[source]

Add or update the canonical URL.

set_description(description: str)[source]

Set meta description content.

set_favicon(source: str, icon_type: str = 'image/png', rel: str = 'icon', sizes: Optional[str] = None)[source]

Add a favicon or icon link tag.

Parameters:
  • source – URL/path to icon file.

  • icon_type – MIME type (e.g. ‘image/png’, ‘image/svg+xml’).

  • rel – ‘icon’, ‘apple-touch-icon’, etc.

  • sizes – Optional icon size string like ‘32x32’.

Returns:

The generated favicon component.

Return type:

NoInnerComponent

set_favicons(icons: List[Dict[str, str]]) List[duck.html.components.NoInnerComponent][source]

Add multiple favicons/touch icons at once.

Parameters:

icons – List of dicts with keys: href (required), rel, type, sizes.

Returns:

List of generated favicons.

Return type:

List[NoInnerComponent]

set_json_ld(data: Dict)[source]

Add JSON-LD structured data script tag.

set_keywords(keywords: List[str])[source]

Set the keywords meta tag.

Parameters:

keywords – The list of keywords.

set_lang(lang: str)[source]

Set HTML lang attribute and Content-Language meta.

Parameters:

lang – Language code like ‘en’, ‘fr’, ‘es-ES’.

set_opengraph(title: Optional[str] = None, description: Optional[str] = None, url: Optional[str] = None, image: Optional[str] = None, type: Optional[str] = None, site_name: Optional[str] = None)[source]

Set OpenGraph meta tags.

set_pagination(prev_url: Optional[str] = None, next_url: Optional[str] = None)[source]

Add pagination links.

Parameters:
  • prev_url – URL of previous page.

  • next_url – URL of next page.

set_product_json_ld(name: str, description: str, sku: str, brand: str, price: str, currency: str, availability: str, url: Optional[str] = None, image: Optional[str] = None)[source]

Add Product JSON-LD structured data.

set_robots(content: str)[source]

Set robots meta tag content. Example: ‘noindex, nofollow’, ‘index, follow’, etc.

set_title(title: str)[source]

Set page title.

set_twitter_card(card: str = 'summary', title: Optional[str] = None, description: Optional[str] = None, image: Optional[str] = None, site: Optional[str] = None, creator: Optional[str] = None)[source]

Add Twitter Card meta tags.

Parameters:
  • card – Type of card (summary, summary_large_image, etc.)

  • title – Card title.

  • description – Card description.

  • image – Image URL.

  • site – Twitter @site.

  • creator – Twitter @creator.

exception duck.html.components.page.PageError[source]

Bases: Exception

Raised when required request context is missing.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception duck.html.components.page.UnrecommendedAddChildWarning[source]

Bases: Warning

Warning that gets flagged when a user try to use add_child on a Page component instead of using add_to_body or add_to_head.

Initialization

Initialize self. See help(type(self)) for accurate signature.

Page Component Module

This module defines the Page component class, a robust foundation for building full HTML pages with advanced SEO, social media integration, accessibility, performance optimizations, and analytics support.

Key Features:

  • Complete HTML page structure with , , and elements.

  • Language and locale configuration through the lang attribute and Content-Language meta tag.

  • SEO-friendly meta tags: title, description, robots, canonical URL, and pagination (prev/next links).

  • Social media metadata support via OpenGraph and Twitter Card tags for rich previews.

  • Support for multiple favicons and Apple Touch Icons, accommodating various device requirements.

  • Ability to add custom stylesheets and JavaScript files, with async and defer attributes.

  • Embedding JSON-LD structured data, with helpers for common types like Article and Product.

  • Simple integration for Google Analytics tracking.

  • Accessibility improvements by setting appropriate roles and language attributes.

  • An ErrorPage subclass for quickly creating customizable error pages.