duck.html.components.scriptยถ

Script HTML Component.

This module defines a reusable Script component for embedding JavaScript code within an HTML document.

Module Contentsยถ

Classesยถ

Script

Script HTML Component.

APIยถ

class duck.html.components.script.Script(element: Optional[str] = None, properties: Optional[Dict[str, str]] = None, props: Optional[Dict[str, str]] = None, style: Optional[Dict[str, str]] = None, inner_html: Optional[Union[str, str, float]] = None, children: Optional[List[duck.html.components.HtmlComponent]] = None, **kwargs)[source]ยถ

Bases: duck.html.components.InnerComponent

Script HTML Component.

The Script component allows developers to embed JavaScript code within an HTML page dynamically. It can be used to define inline scripts that interact with other components.

Features:

  • Supports inline JavaScript execution.

  • Can be dynamically added to any component.

  • Provides flexibility for defining custom client-side logic.

Example Usage:

script = Script(
    inner_html='''
        function showAlert() {
            alert("Hello, world!");
        }
    '''
)
component.add_child(script)

This will generate the following HTML output:

<script>
    function showAlert() {
        alert("Hello, world!");
    }
</script>

Notes:

  • Automatic Nonce Addition: When ENABLE_HEADERS_SECURITY_POLICY=True and csp_nonce_flag is set in CSP_TRUSTED_SOURCES, the nonce property is automatically added.

  • Request Resolution Required: For the nonce to be set automatically, the request must be resolved. This is achieved by calling get_request_or_raise on the component root (or the current component if the root is None).

Initialization

Initialize an HTML component.

Parameters:
  • element โ€“ The HTML element tag name (e.g., textarea, input, button). Can be None, but make sure element is returned by get_element method.

  • accept_inner_html โ€“ Whether the HTML component accepts an inner body (e.g., inner-body-here).

  • inner_html โ€“ Inner html to add to the HTML component. Defaults to None.

  • properties โ€“ Dictionary for properties to initialize the component with.

  • props โ€“ Just same as properties argument (added for simplicity).

  • style โ€“ Dictionary for style to initialize the component with.

  • **kwargs โ€“ Extra keyword arguments

Raises:

HtmlComponentError โ€“ If โ€˜elementโ€™ is not a string or โ€˜inner_htmlโ€™ is set but โ€˜accept_inner_htmlโ€™ is False.

get_element()[source]ยถ

Returns the HTML tag for the component.

property propertiesยถ
set_csp_nonce()[source]ยถ

This tries to retrieve current request nonce.