duck.html.components.page¶
Module Contents¶
Classes¶
Basic error page with customizable status code and message. |
|
Class representing an event handler chain. |
|
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.PageBasic error page with customizable status code and message.
Initialization
Initialize the Page component.
- Parameters:
request – The target HTTP request.
disable_lively – This disables
Livelycomponents 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.
- 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.PageErrorRaised 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.InnerComponentFull-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
Livelycomponents 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_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.comin 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_bindis 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_selfis False and noupdate_targetsare 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:
DOMContentLoadedDuckNavigatedYou can bind listeners to these events to perform cleanup actions, such as closing open components (dropdowns, modals, etc.).
Unbinding document event handlers using
document_unbindonly 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 thedocument_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_unbindonly 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 thedocument_unbind).
- get_document_event_info(event: str) Tuple[Callable, Set[HtmlComponent]][source]¶
Returns the event info in form: (event_handler, update_targets).
- get_request_or_raise() HttpRequest[source]¶
Retrieves a request object from component
kwargsor raise an exception.- Raises:
RequestNotFoundError – If the request is not in kwargs or kwargs[‘context’] (if used in templates).
- 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_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_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_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.
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
langattribute 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
ErrorPagesubclass for quickly creating customizable error pages.
Recommended Usage Pattern:¶
To maintain clean, maintainable, and reusable code, it is strongly encouraged
to create your own page components by subclassing Page.
Override the on_create() method in your subclass to set page-specific metadata,
manage favicons, add scripts/styles, and define body content.
Example subclass:
class HomePage(Page):
def on_create(self):
super().on_create()
self.set_author("My Name")
self.set_title("Home - MySite")
self.set_description("Welcome to MySite, the premier platform for ...")
self.set_favicon("/static/favicon.ico")
self.set_opengraph(
title="Home - MySite",
description="Welcome to MySite, the premier platform for ...",
url="https://mysite.com",
image="https://mysite.com/og-image.png",
type="website",
site_name="MySite"
)
self.set_twitter_card(card="summary_large_image", title="Home - MySite")
self.set_json_ld({
"@context": "https://schema.org",
"@type": "WebSite",
"url": "https://mysite.com",
"name": "MySite",
"description": "Welcome to MySite, the premier platform for ..."
})
# Add additional custom head or body components here as needed
Notes:
For all page methods, esp those that has
set*oradd*prefix e.g. These methods may override existing component if called more than once. Not all methods can do this, others may just return the component generated from using that method. You can store the components from such methods for later deletion in cases you wanna override in different page.To avoid partial page reload and do a fullpage reload on certain page, just set attribute
fullpage_reloadto True.Whenever headers like
Set-Cookieis found in component response, a fullpage reload is triggered. Just modify page’sfullpage_reload_headers.
By organizing your pages this way, you isolate page-specific logic inside dedicated classes, making your code easier to maintain, extend, and debug.
Example use case
# in your views
from duck.shortcuts import to_response
def home(request):
homepage = HomePage(request=request)
return to_response(homepage)
This module is designed to be flexible and integrates well within Duck projects or other Python web frameworks employing component-based rendering.