MIXT documentation: API

PropTypes

PropTypes are at the heart of Mixt. The aim si to specify precisely what kind of data a component is allowed to receive.

It is then "strongly typed" (sort of). And of course largely inspired by React.

It works by defining a class named PropTypes inside your components. (see full example below).

Then, you must define the type (using the python typing syntax), and, if you want, a default value. The format is prop_name: type or prop_name: type = default.

Special types

Required

By default all props are optional. Enclosing a prop type with Required[] make it... required.

Note: A required prop cannot have a default value.

Example
>>> from mixt import Required
>>> class Component(Element):
...     class PropTypes:
...         optional_prop: str
...         required_prop: Required[str]

Choices

Choices allows to define a list of acceptable value.

In the PropTypes class, Choices is used as the type. And the value of this prop is the list of choices.

Example
>>> from mixt import Choices
>>> class Component(Element):
...     class PropTypes:
...         size: Choices = ['XS', 'S', 'M', 'L', 'XL', 'XXL']

DefaultChoices

DefaultChoices is like Choices but the first entry will be the default prop value.

Example
>>> from mixt import DefaultChoices
>>> class Component(Element):
...     class PropTypes:
...         size: DefaultChoices = ['XS', 'S', 'M', 'L', 'XL', 'XXL']

>>> <Component />.size
'XS'

Special values

Booleans

boolean props are handled specifically.

A boolean can be passed:

  • in python (<Comp flagged={False} />, <Comp flagged={bool_value} />)

  • as a string (<Comp flagged=false />, <Comp flagged='false' />)

  • without value (<Comp flagged />): it is then True

  • with a empty string (<Comp flagged='' />): it is then True

  • with the name of the prop as value (<Comp flagged='flagged' />): it is then True

All other case are not valid. Passing without attribute, or with empty string or name of the prop as value is inspired by HTML boolean attributes.

Example
>>> class Component(Element):
...     class PropTypes:
...         flagged: bool = False

>>> <Component />.flagged
False
>>> <Component flagged />.flagged
True
>>> <Component flagged=true />.flagged
True
>>> <Component flagged="true" />.flagged
True
>>> <Component flagged=TRUE />.flagged
True
>>> <Component flagged={True} />.flagged
True
>>> <Component flagged="" />.flagged
True
>>> <Component flagged="flagged" />.flagged
True
>>> <Component flagged="other" />
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropBoolError: <Component>.flagged: `other` is not a valid choice for this boolean prop (must be in [True, False, 'true', 'false', '', 'flagged'])
>>> <Component flagged=false />.flagged
False
>>> <Component flagged="false" />.flagged
False
>>> <Component flagged=FALSE />.flagged
False
>>> <Component flagged={False} />.flagged
False

Numbers

Numbers (int and float) can be passed as string, and numbers can be passed to strings.

Example
>>> class Component(Element):
    class PropTypes:
        num: int
        string: str

>>> <Component num=1 />.num
1
>>> <Component num="1" />.num
1
>>> <Component num={1} />.num
1
>>> <Component num={"1"} />
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropValueError: <Component>.num: `1` is not a valid value for this prop (type: <class 'str'>, expected: <class 'int'>)
>>> <Component string=1 />.string
'1'
>>> <Component string={1} />.string
'1'

None

None will be interpreted as python None if passed directly or as string.

It is important to note the difference between None and NotProvided.

None is actually a value, and cannot be passed to a prop not having None as possible type.

Example
>>> class Component(Element):
...     class PropTypes:
...         string: str
...         string_or_none: Union[None, str]

>>> <Component string_or_none=None />.string_or_none
None
>>> <Component string_or_none="None" />.string_or_none
None
>>> <Component string_or_none={"None"} />.string_or_none
'None'
>>> <Component string=None />.string
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropValueError: <Component>.string: `None` is not a valid value for this prop (type: <class 'NoneType'>, expected: <class 'str'>)
>>> <Component string="None" />.string
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropValueError: <Component>.string: `None` is not a valid value for this prop (type: <class 'NoneType'>, expected: <class 'str'>)
>>> <Component string="None" />.string
'None'

NotProvided

Passing NotProvided (directly, in python or as a string) to a prop is equal to not pass it anything. The prop won't be set.

Example
>>> from mixt import NotProvided

>>> class Component(Element):
...     class PropTypes:
...         string: str

>>> <Component string=NotProvided />.string
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Component>.string: prop is not set

>>> <Component string={NotProvided} />.string
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Component>.string: prop is not set

>>> <Component string="NotProvided" />.string
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Component>.string: prop is not set

value = NotProvided
>>> <Component string={value} />.string
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Component>.string: prop is not set

value = "NotProvided"
<Component string={value} />.string
'NotProvided'

Element

Base element for reusable components.

PropTypes

Default props for all elements.

Props

ref: Ref

A reference to the element itself that can be used later. See Ref for more information.

id: str

The id of the element. It will not be passed down the tree like _class.

_class: str

A string containing the "class" html attribute that will be passed down to the first rendered html element.

Example

>>> class Component(Element):
...    def render(self, context):
...        return <div id={self.id}>Hello</div>

>>> print(<Component class="some class" id="FOO" />)
<div id="FOO" class="some class">Hello</div>

Example

# In pure python:

>>> from mixt import Element, Required, html

>>> class Greeting(Element):
...     class PropTypes:
...         name: Required[str]
...
...     def render(self, context):
...        return html.Div(
...            'Hello, ',
...            html.Strong()(self.name)
...        )

>>> print(<Greeting name='World' />)
<div>Hello, <strong>World</strong></div>

# In "mixt", aka 'html in python":
# Notes: "html in python" does not work in a python shell, only in files.
# And you must import ``html`` from ``mixt`` to use normal html tags.

>>> #  coding: mixt

>>> from mixt import Element, Required, html

>>> class Greeting(Element):
...     class PropTypes:
...         name: Required[str]
...
...     def render(self, context):
...        return <div>Hello, <strong>{self.name}</strong></div>

>>> print(<Greeting name='World' />)
<div>Hello, <strong>World</strong></div>

# And to show how the ``__tag__`` and ``__display_name__`` attributes are composed by default:
>>> Greeting.__tag__
'Greeting'

>>> Greeting.__display_name__
'Greeting'

Attributes

__tag__: str = 'Element'

The tag to use when using the element in "html". If not set in the class, it will be, by default, the name of the class itself.

__display_name__: str = 'Element'

A "human" representation of __tag__. Will be used in exceptions and can be changed to give more information.

Methods

prop(name: str, default: Any = NotProvided) → Any

Return a prop defined by name, if it is defined, or the default if provided.

Details

If the prop exists but is not set, default is not provided, and the prop has a default value, this default value is returned.

Calling el.prop("name") is the same as calling el.name.

Arguments
name: str

The name of the wanted prop.

default: Any = 'NotProvided'

The value to return if the prop is not set. If NotProvided, the default value set in PropTypes is used. Else we raise.

Returns
Any

The value of the prop or a default one.

Raises

If the prop is not set and no default value is available.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> <Greeting />.prop("name")
'World'
>>> <Greeting />.name
'World'

>>> <Greeting />.prop("surname")
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Greeting>.surname: prop is not set

>>> <Greeting />.surname
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Greeting>.surname: prop is not set

>>> <Greeting />.prop("surname", "J")
'J'
>>> <Greeting surname="JJ"/>.prop("surname")
'JJ'
>>> <Greeting name="John"/>.prop("name")
'John'

>>> <Greeting />.prop("firstname")
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

>>> <Greeting />.firstname
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

@classmethod
prop_name(name: str) → str

Return the corrected name for the prop defined by name, if the prop exists.

Details

For example, if name is "class", it will return "_class". If "data-foo", it will return "data_foo".

Arguments
name: str

The name we want to validate.

Returns
str

The real name of the given prop.

Raises

If there is no prop with the given name.

Example
>>> class Component(Element):
...     class PropTypes:
...         some_name: str

>>> Component.prop_name('some-name')
'some_name'
>>> Component.prop_name('class')
'_class'

has_prop(name: str, allow_invalid: bool = True) → bool

Tell if the prop defined by name is defined (or has a default value.

Details
Arguments
name: str

The name of the prop to check.

allow_invalid: bool = True

If set to True, it will return False if the name if for a prop that is not allowed. Else if will raise InvalidPropNameError.

Returns
bool

True if the prop is defined, False otherwise.

Raises

If there is no prop with the given name and allow_invalid is False.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> <Greeting />.has_prop("name")
True
>>> <Greeting />.has_prop("surname")
False
>>> <Greeting surname="J"/>.has_prop("surname")
True
>>> <Greeting name="John"/>.has_prop("name")
True

>>> <Greeting />.has_prop("firstname")
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

>>> <Greeting />.has_prop("firstname", allow_invalid=True)
False

set_prop(name: str, value: Any) → Any

Set the value of the prop defined by name, if it is valid.

Details

The value is validated only if not in dev-mode. But still converted if needed, like for booleans. If value is NotProvided, the prop is unset.

Arguments
name: str

The name of the prop to set.

value: Any

The value to set to the prop. If set to NotProvided, this will unset the actual set value for this prop.

Returns
Any

If value is not NotProvided returns the value that is really set. It may have been changed by the validation process. If value is NotProvided, returns the value that was stored in the prop before deleting it.

Raises

If the value is not valid.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> el = <Greeting />
>>> el.set_prop("name", "John")
>>> el.name
'John'

>>> el.set_prop("name", {"first": "John"})
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropValueError: <Greeting>.name: `{'first': 'John'}` is not a
valid value for this prop (type: <class 'dict'>, expected: <class 'str'>)

>>> el.set_prop("firstname", "John")
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

unset_prop(name: str) → Any

Unset the actual value of the prop defined by name.

Details
Arguments
name: str

The name of the prop to unset.

Returns
Any

The value that was stored in the prop before deleting it.

Raises

If there is no prop with the given name.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> el = <Greeting />
>>> el.set_prop("name", "John")
>>> el.name
'John'

>>> el.unset_prop("name")
>>> el.name
'World'

>>> el.set_prop("surname", "JJ")
>>> el.surname
'JJ'

>>> el.unset_prop("surname")
>>> el.surnname
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Greeting>.surname: prop is not set

>>> el.unset_prop("firstname")
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

prop_default(name: str) → Any

Return the default value of the prop defined by name.

Details
Arguments
name: str

The name of the prop for which we want the default value

Returns
Any

The default value defined in PropTypes or NotProvided if not set.

Raises

If there is no prop with the given name.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> <Greeting />.prop_default("name")
'World'

>>> <Greeting />.prop_default("surname")
<class 'mixt.proptypes.NotProvided'>

>>> <Greeting />.prop_default("firstname")
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

is_prop_default(name: str, value: Any = NotProvided) → bool

Tell if the actual (or given) value for the prop defined by name is the default one.

Details
Arguments
name: str

The name of the prop we are asking for.

value: Any = 'NotProvided'

If set, will use this value to check if it is the default one. Else (if NotProvided), it will use the actual prop.

Returns
bool

True if the given value or the prop value is the default one, False otherwise.

Raises

If there is no prop with the given name.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> <Greeting />.is_prop_default("name", "John")
False
>>> <Greeting />.is_prop_default("name", "World")
True
>>> <Greeting />.is_prop_default("name")
True

>>> <Greeting name="John"/>.is_prop_default("name", "World")
True
>>> <Greeting name="John"/>.is_prop_default("name", "John")
False
>>> <Greeting name="John"/>.is_prop_default("name")
False

>>> <Greeting />.is_prop_default("surname")
Traceback (most recent call last):
...
mixt.exceptions.UnsetPropError: <Greeting>.surname: prop is not set

>>> <Greeting />.is_prop_default("surname", "JJ")
False
>>> <Greeting surname="JJ" />.is_prop_default("surname")
False

@classmethod
prop_type(name: str) → Any

Return the type of the prop defined by name.

Details
Arguments
name: str

The name of the prop we want the type

Returns
Any

The type, coming from PropTypes

Raises

If there is no prop with the given name.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> Greeting.prop_type("name")
<class 'str'>
>>> Greeting.prop_type("surname")
<class 'str'>
>>> Greeting.prop_type("firstname")
Traceback (most recent call last):
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

@classmethod
is_prop_required(name: str) → bool

Tell if the prop defined by name is a required one.

Details
Arguments
name: str

The name of the prop we want to know if it is required.

Returns
bool

True if the prop is required, False otherwise.

Raises

If there is no prop with the given name.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: Required[str]

>>> Greeting.is_prop_required("name")
False
>>> Greeting.is_prop_required("surname")
True
>>> Greeting.is_prop_required("firstname")
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

set_props(props: Dict[str, Any]) → None

Set some props in addition/replacement to the already set ones.

Details
Arguments
props: Dict[str, Any]

A dict with each prop to set. If a prop is already set, it will be replaced.

Returns
None
Raises

If a value is not valid (if dev-mode)

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> el = <Greeting />
>>> el.set_props({"name": "John", "surname": "JJ"})
>>> el.name
'John'
>>> el.surname
'JJ'

>>> el.set_props({"name": {"first": "John"}})
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropValueError: <Greeting>.name: `{'first': 'John'}` is not a
valid value for this prop (type: <class 'dict'>, expected: <class 'str'>)

>>> el.set_props({"firstname": "John"})
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropNameError: <Greeting>.firstname: is not an allowed prop

@property
props → Props

Get all the available and set props, including default ones.

Details
Returns
Props

A dict with each defined props. If a prop is not set but has a default value, this one is used.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str

>>> <Greeting />.props)
{'name': 'World'}

>>> <Greeting name="John" surname="JJ"/>.props)
{'name': 'John', 'surname': 'JJ'}

props_for(component: Type[Base]) → Dict[str, Any]

Get the props defined for the given component.

Details

Used when using ElementProxy to get the props of the proxied and the base.

Arguments
component: Type[Base]

The component for which we want to restrict the props

Returns
Dict[str, Any]

The dict of properties limited to the one of the given component.

Raises

If the component is not an Element or an HtmlElement

Example
>>> class Component(ElementProxy):
...     class PropTypes:
...         val: int
>>> ComponentForCanvas = Component.For(html.Canvas)
>>> obj = ComponentForCanvas(val=3, height=300)
>>> obj.props
{'val': 3, 'height': 300}
>>> obj.props_for(html.Canvas)
{'height': 300}
>>> obj.props_for(Component)
{'val': 3}

@property
declared_props → Props

Get the props that are declared in PropTypes (no data_* and aria_*).

Details
Returns
Props

The props limited to the ones declared in PropTypes.

Example
>>> class Component(Element):
...     class PropTypes:
...         val: int
>>> obj = Component(val=3, data_foo="bar", aria_disabled="true")
>>> obj.props
{'val': 3, 'data_foo': 'bar', 'aria_disabled': 'true'}
>>> obj.declared_props
{'val': 3}

@property
non_declared_props → Props

Get the props that are not declared in PropTypes (only data_* or aria_*).

Details
Returns
Props

The props limited to the non declared ones.

Example
>>> class Component(Element):
...     class PropTypes:
...         val: int
...         data_val: int
...         aria_val: int
>>> obj = Component(val=3, data_val=1, data_foo="bar", aria_val=2, aria_disabled="true")
>>> obj.props
{'val': 3, 'data_val': 1, 'data_foo': 'bar', 'aria_val': 2, 'aria_disabled': 'true'}
>>> obj.non_declared_props
{'data_foo': 'bar', 'aria_disabled': 'true'}

prefixed_props(prefix: str) → Dict[str, Any]

Get the props matching the given prefix.

Details
Arguments
prefix: str

The prefix to match.

Returns
Dict[str, Any]

The props limited to the ones starting with prefix.

Example
>>> class Compoment(Element):
...     class PropTypes:
...         foo: str
...         val1: int
...         val2: int
>>> obj = Component(foo='bar', val1=11, val2=22)
>>> obj.props
{'foo': 'bar', 'val1': 11, 'val2': 22}
>>> obj.prefixed_props('val')
{'val1': 11, 'val2': 22}

to_string() → str

Convert the element into an html string.

Details
Returns
str

The html ready to be used.

Example
>>> class Greeting(Element):
...     class PropTypes:
...         name: str = "World"
...         surname: str
...
...     def render(self, context):
...         return <div>Hello, <strong>{self.name}</strong></div>

>>> <Greeting />.to_string()
<div>Hello, <strong>World</strong></div>

# It's what is actually called when using ``str(...)``
>>> str(<Greeting />)
<div>Hello, <strong>World</strong></div>

children(selector: Union[str, Type[Base], None] = None, exclude: bool = False) → List[Union[Base, str, Callable]]

Return the (direct) children, maybe filtered.

Details
Arguments
selector: Union[str, Type[Base], None] = None

Empty by default. Used to filter the children.

If it's a string to specify how to filter the children:

  • If it starts with a dot ., we select children having this class.

  • If it starts with a sharp #, we select children having this id.

  • Else we select children having this tag name.

If it's a class, only instances of this class (or subclass) are returned

exclude: bool = False

False by default. If True, the result of the selection done by selector is reversed. Ie we select ALL BUT children having this class/id/tag.

Returns
List[Union[Base, str, Callable]]

A List, maybe empty, of all the children, maybe filtered.

Example
>>> class Details(Element):
...    def render(self, context):
...        p_element = self.children(html.P)
...        other_children = self.children(html.P, exclude=True)
...        return <details>
...            <summary>{p_element}</summary>
...            {other_children}
...        </details>

append(child_or_children: Union[Base, str, Callable, List[Union[Base, str, Callable]]]) → None

Append some children to the current element.

Details

In the process, we propagate the actual context to the children.

Arguments
child_or_children: Union[Base, str, Callable, List[Union[Base, str, Callable]]]

The child(ren) to add.

Returns
None
Example
>>> class AddNote(Element):
...     class PropTypes:
...         note: Required[str]
...     def prerender(self, context):
...         self.append(<aside class="note">Note: {self.note}</aside>)

>>> print(<div><AddNote note="you're welcome"><p>Hello, John</p></AddNote></div>)
<div><p>Hello, John</p><aside class="note">Note: you're welcome</aside></div>

prepend(child_or_children: Union[Base, str, Callable, List[Union[Base, str, Callable]]]) → None

Prepend some children to the current element.

Details

In the process, we propagate the actual context to the children.

Arguments
child_or_children: Union[Base, str, Callable, List[Union[Base, str, Callable]]]

The child(ren) to add.

Returns
None
Example
>>> class Title(Element):
...     class PropTypes:
...         text: Required[str]
...         level: Required[int]
...     def prerender(self, context):
...         self.prepend(<h level={self.level}>{self.text}</h>)

>>> print(<Title text="Welcome" level=1><p>Hello, John</p></Title>)
<h1>Welcome</h1><p>Hello, John</p>

remove(child_or_children: Union[Base, str, Callable, List[Union[Base, str, Callable]]]) → None

Remove some children from the current element.

Details
Arguments
child_or_children: Union[Base, str, Callable, List[Union[Base, str, Callable]]]

The child(ren) to remove.

Returns
None
Example
>>> class NoHr(Element):
...     def prerender(self, context):
...     self.remove(self.children(html.Hr))

>>> print(<NoHr><p>Foo</p><hr /><p>Bar</p><hr /><p>Baz</p></NoHr>)
<p>Foo</p><p>Bar</p><p>Baz</p>

add_class(klass: str, prepend: bool = False) → str

Add the given class(es) (klass) to the actual list of classes.

Details
Arguments
klass: str

The class to add. If contains spaces, it will be a list of classes.

prepend: bool = False

If False (the default), the new class(es) will be added at the end of the existing list. If True, it/they will be added at the beginning.

Returns
str

The new value of the class prop.

Example
>>> class Component(Element):
...     pass

>>> el = <Component />
>>> el.add_class("foo")
>>> el.classes
['foo']

>>> el.add_class("bar baz")
>>> el.classes
['foo', 'bar', 'baz']

>>> el.add_class("zab rab", prepend=True)
>>> el.classes
['zab', 'rab', 'foo', 'bar', 'baz']

append_class(klass: str) → str

Add the given class(es) (klass) to the end of the actual list of classes.

Details
Arguments
klass: str

The class to add. If contains spaces, it will be a list of classes.

Returns
str

The new value of the class prop.

Example
>>> class Component(Element):
...     pass

>>> el = <Component />
>>> el.append_class("foo")
>>> el.classes
['foo']

>>> el.append_class("bar baz")
>>> el.classes
['foo', 'bar', 'baz']

prepend_class(klass: str) → str

Add the given class(es) (klass) to the beginning of the actual list of classes.

Details
Arguments
klass: str

The class to add. If contains spaces, it will be a list of classes.

Returns
str

The new value of the class prop.

Example
>>> class Component(Element):
...     pass

>>> el = <Component />
>>> el.prepend_class("foo")
>>> el.classes
['foo']

>>> el.prepend_class("bar baz")
>>> el.classes
['bar', 'baz', 'foo']

remove_class(klass: str) → str

Remove the given class(es) (klass) from the actual list of classes.

Details
Arguments
klass: str

The class to remove. If contains spaces, it will be a list of classes.

Returns
str

The new value of the class prop.

Example
>>> class Component(Element):
...     pass

>>> el = <Component class="foo bar"/>
>>> el.remove_class("baz")
>>> el.classes
['foo', 'bar']

>>> el.remove_class("bar")
>>> el.classes
['foo']

>>> el.remove_class("foo bar baz")
>>> el.classes
[]

has_class(klass: str) → bool

Tell if the given class is in the actual list of classes.

Details
Arguments
klass: str

The class to check.

Returns
bool

The new value of the class prop.

Example
>>> class Component(Element):
...     pass

>>> el = <Component class="foo"/>
>>> el.has_class("foo")
True
>>> el.has_class("bar")
True

@property
classes → List[str]

Return a list of the classes defined in the "class" prop, or an empty list if not set.

Details
Returns
List[str]

List of all the classes defined in the "class" prop.

Example
>>> class Component(Element):
...     pass

>>> <Component />.classes
[]
>>> <Component class="foo bar" />.classes
['foo', 'bar']

render(context: Union[BaseContext, None]) → Union[Base, str, Callable, List[Union[Base, str, Callable]], None]

Return elements to be rendered as html.

Details

Returns only all children (self.children()) by default.

Must be implemented in subclasses to do something else.

Must return a component, a list of components, a fragment, or False/None. See example for more details.

Arguments
context: Union[BaseContext, None]

The context passed through the tree.

Returns
Union[Base, str, Callable, List[Union[Base, str, Callable]], None]

None, or one or many elements or strings.

Example
# It can return a single element (a normal html tag or another component),
# which can have children:
>>> class Greeting(Element):
...     class PropTypes:
...         name: Required[str]
...
...     def render(self, context):
...         return <div>Hello, <strong>{self.name}</strong>{self.children()}</div>

>>> print(<Greeting name="John">, you look great today!</Greeting>)
<div>Hello, <strong>John</strong>, you look great today!</div>

# It can return many nodes, using ``<Fragment>``:
>>>     def render(self, context):
...         return <Fragment>
...             <div>Foo</div>
...             <div>Bar</div>
...         </Fragment>
<div>Foo</div><div>Bar</div>

# It can return many nodes, using an iterable (note the commas after each entry). The
# main purpose is to be able to compose the list before calling ``return``:
>>>     def render(self, context):
...         return [
...             <div>Foo</div>,
...             <div>Bar</div>,
...         ]
<div>Foo</div><div>Bar</div>

# It can return a simple string:
>>>     def render(self, context):
...         return "Foo Bar"
Foo Bar

# And a list of strings:
>>>     def render(self, context):
...         return ["Foo", "Bar"]
FooBar

# ``False`` and ``None`` are ignored:
>>>     def render(self, context):
...         return [
...             False,
...             <div>Foo</div>,
...             None,
...             <div>Bar</div>,
...         ]
<div>Foo</div><div>Bar</div>

# All of these rules can be mized up.
# Note how lists can be used not only at the first level:
>>>     def render(self, context):
...         return [
...             False,
...             [
...                 <div>Foo</div>,
...                 <div>Bar</div>,
...             ],
...             None,
...             "Baz"
...         ]
<div>Foo</div><div>Bar</div>Baz

prerender(context: Union[BaseContext, None]) → None

Provide a hook to do things before the element is rendered.

Details

Default behavior is to do nothing.

Arguments
context: Union[BaseContext, None]

The context passed through the tree.

Returns
None
Example
>>> class Component(Element):
...     def prerender(self, context):
...         self.started_at = datetime.utcnow()
...         print(f"Rendering <{self.__display_name__}>...")
...     def postrender(self, element, context):
...         duration = datetime.utcnow() - self.started_at
...         print(f"Rendered <{self.__display_name__}> in {duration}")

postrender(element: Union[Base, str, Callable], context: Union[BaseContext, None]) → None

Provide a hook to do things after the element is rendered.

Details

Default behavior is to do nothing. See prerender for an example.

Arguments
element: Union[Base, str, Callable]

The element rendered by render. Could be an Element, an html tag, a RawHtml...

context: Union[BaseContext, None]

The context passed through the tree.

Returns
None

postrender_child_element(child: Element, child_element: Union[Base, str, Callable], context: Union[BaseContext, None]) → None

Provide a hook for every parent to do things after any child is rendered.

Details

Default behavior is to do nothing. Useful to collect stuff for delayed rendering (see CSSCollector and JSCollector), stats...

Arguments
child: Element

The element in a tree on which render was just called.

child_element: Union[Base, str, Callable]

The element rendered by the call of the render method of child.

context: Union[BaseContext, None]

The context passed through the tree.

Returns
None
Example
>>> class ComponentCounter(Element):
...     def __init__(self, **kwargs):
...         self.count = defaultdict(int)
...         super().__init__(**kwargs)
...
...     def postrender_child_element(self, child, child_element, context):
...         self.count[child.__class__.__name__] += 1

>>> counter = Ref()
>>> print(
...     <ComponentCounter ref={counter}>
...         <div>
...             Rendered:
...             {lambda: str(dict(counter.current.count))}
...         </div>
...         <Greeting name='World'/>
...         <Greeting name='John'/>
...     </ComponentCounter>
... )
<div>Rendered: {'Greeting': 2}</div><div>Hello, <strong>World</strong></div><div>Hello,
<strong>John</strong></div>

add_ref() → Ref

Create and return a new Ref object.

Details
Returns
Ref

The ref, without value, ready to be set.

Example
# This:
>>> class Component(Element):
...     def render(self, context):
...         some_ref = self.add_ref()

# Is exactly the same as:
>>> from mixt import Ref
>>> class Component(Element):
...     def render(self, context):
...         some_ref = Ref()

# It will simply avoid an import.

# See ``Ref`` documentation to know more about refs.

ElementProxy

A subclass of Element that is a proxy to another.

PropTypes

ref: Ref

A reference to the element itself that can be used later. See Ref for more information.

id: str

The id of the element. It will not be passed down the tree like _class.

_class: str

A string containing the "class" html attribute that will be passed down to the first rendered html element.

Example

# You can define a proxy for an html element. Using `ElementProxy.For` allows to have
# a default proxied element. Without `.For`, the new proxy will need to be called later
# with `.For`.

>>> class Button(ElementProxy.For(html.Button)):
...     class PropTypes:
...         label: str = 'button'
...     def render(self, context):
...         # we pass the the proxied element its own props
...         return self.proxied(**self.proxied_props)(
...             html.Span()(self.label)
...         )

# The "props" value is for the button element.
>>> str(Button(value=1)) == '<button value="1"><span>button</span></button>'

# To change the proxied element, use `For`:
>>> str(Button.For(html.Div)("ok")) == '<div><span>ok</span></div>'

Attributes

proxied: Type[Base] = None

The proxied component to be used in render. It's the one passed to the For method.

Methods

@classmethod
For(component: Type[Base]) → Type[ElementProxy]

Return a new version of this proxy, for the given element to proxy.

Details
Arguments
component: Type[Base]

The element be be proxied

Returns
Type[ElementProxy]

A new version of this proxy

@property
proxied_props → Props

Get the props for the proxied element (with data_* and aria_*).

Details
Returns
Props

The props limited to the ones for the proxied element and non declared ones.

Example
>>> class Component(ElementProxy):
...     class PropTypes:
...         val: int
>>> ComponentForCanvas = Component.For(html.Canvas)
>>> obj = ComponentForCanvas(val=3, height=300, data_foo=1)
>>> obj.props
{'val': 3, 'height': 300, 'data_foo': 1}
>>> obj.proxied_props
{'height': 300, data_foo: 1}

@property
own_props → Props

Get the props for the base proxy element (no data_* and aria_*).

Details
Returns
Props

The props limited to the ones for the base proxy element.

Example
>>> class Component(ElementProxy):
...     class PropTypes:
...         val: int
>>> ComponentForCanvas = Component.For(html.Canvas)
>>> obj = ComponentForCanvas(val=3, height=300, data_foo: 1)
>>> obj.props
{'val': 3, 'height': 300, data_foo: 1}
>>> obj.own_props
{'val': 3}

Ref

An object storing the reference to an element.

The goal is to use it later, once the element is rendered. For example by "collectors", like the first example below (or CSSCollector and JSCollector).

Example

>>> class ComponentCounter(Element):
...     def __init__(self, **kwargs):
...         self.count = defaultdict(int)
...         super().__init__(**kwargs)
...
...     def postrender_child_element(self, child, child_element, context):
...         self.count[child.__class__.__name__] += 1

>>> counter = Ref()

# Here we use the ref to display data from the referenced component, once it is rendered.
# Without this, it would not be possible. Also note the ``lambda``: this is mandatory
# because without it, we would not have the finalized data.

>>> print(
...     <ComponentCounter ref={counter}>
...         <div>
...             Rendered:
...             {lambda: str(dict(counter.current.count))}
...         </div>
...         <Greeting name='World'/>
...         <Greeting name='John'/>
...     </ComponentCounter>
... )
<div>Rendered: {'Greeting': 2}</div><div>Hello, <strong>World</strong></div><div>Hello,
<strong>John</strong></div>

# Another example, using a ref inside the ``render`` method to, for example,
# access it in ``postrender``.
# Using ``ref = self.add_ref()`` in an element is the same as using ``ref = Ref()``.

>>> class Greeting(Element):
...     class PropTypes:
...         name: Required[str]
...
...     def render(self, context):
...         self.strong_ref = self.add_ref()
...         return <div>Hello, <strong ref={self.strong_ref}>{self.name}</strong></div>
...
...     def postrender(self, element, context):
...         self.strong_ref.current.add_class('very-strong')

>>> print(<Greeting name="John"></Greeting>)
<div>Hello, <strong class="very-strong">John</strong></div>

Methods

@property
current → Optional[Base]

Get the actual value of this ref.

Details
Returns
Optional[Base]

If the ref was set, return the saved value, else None.

dev_mode

Functions to get/activate/deactivate dev-mode.

In "dev-mode", active by default, a lots of costly checks will be done when trying to set the props of elements to ensure that the types match the ones defined in PropTypes.

It's active by default to let you be sure that your code is correct.

Your tests must run in "dev-mode".

But in production, you trust your tests, and don't need to enforce type checking of your props.

And as "costly" means "time" or "money", you are encouraged to deactivate the "dev-mode" in production.

The included functions can be imported from mixt.dev_mode or, by convenience, from mixt.

Example

# This example shows how in non-dev mode, props are not validated.
# This should of course be covered by tests so this cannot happen.

>>> class Greeting(Element):
...     class PropTypes:
...         name: Required[str]
...
...     def render(self, context):
...         return <div>Hello, <strong>{self.name}</strong></div>

>>> print(in_dev_mode())  # dev-mode is on by default
True

>>> wrong_data = {"firstname": "John"}
>>> print(<Greeting name={wrong_data} />)
Traceback (most recent call last):
...
mixt.exceptions.InvalidPropValueError: <Greeting>.name: `{'firstname': 'John'}` is not a valid
value for this prop (type: <class 'dict'>, expected: <class 'str'>)

>>> with override_dev_mode(False):
...     print(in_dev_mode())
...     print(<Greeting name={wrong_data} />)
False
<div>Hello, <strong>{'firstname': 'John'}</strong></div>

Functions

set_dev_mode(dev_mode: bool = True) → None

Change the dev-mode. Activate it if dev_mode is not defined.

Details
Arguments
dev_mode: bool = True

The new dev mode wanted. Default to True. Will be casted to bool.

Returns
None
Example
>>> from mixt import set_dev_mode, in_dev_mode
>>> in_dev_mode()
True
>>> set_dev_mode(False)
>>> in_dev_mode()
False
>>> set_dev_mode()
>>> in_dev_mode()
True

unset_dev_mode() → None

Deactivate the dev-mode.

Details
Returns
None
Example
>>> from mixt import unset_dev_mode, in_dev_mode
>>> in_dev_mode()
True
>>> unset_dev_mode()
>>> in_dev_mode()
False

override_dev_mode(dev_mode: bool) → Any

Create a context manager to change the dev-mode in a with block.

Details
Arguments
dev_mode: bool

The dev-mode wanted inside the with block.

Returns
Any
Example
>>> from mixt import override_dev_mode, in_dev_mode
>>> in_dev_mode()
True
>>> with override_dev_mode(False):
...     print('off:', in_dev_mode())
...     with override_dev_mode(True):
...         print('on:', in_dev_mode())
...     print('back off:', in_dev_mode())
... print('back on:', in_dev_mode())
off: False
on: True
back off: False
back on: True

in_dev_mode() → bool

Return the actual dev-mode.

Details
Returns
bool

The value of the actual dev-mode.

Example
>>> from mixt import set_dev_mode, unset_dev_mode, in_dev_mode
>>> in_dev_mode()
True
>>> unset_dev_mode()
>>> in_dev_mode()
False
>>> set_dev_mode()
>>> in_dev_mode()
True

Context

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

In a typical Mixt application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme, authenticated user...) that are required by many components within an application.

Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

A context is a simple element than simply render its children, passing itself down the tree. So every element in a tree under a context, gain this context.

You cannot pass anything to a context. A context has a PropTypes class defining the expected props and their types.

You can have many contexts in the tree. They are merged so their children elements can access props of all of them. You just cannot set the same prop in these different contexts.

Example

>>> from mixt import BaseContext, Element, NotProvided, html

>>> class AuthenticatedContext(BaseContext):
...     class PropTypes:
...         auth_username: str
        
>>> class App(Element):
...     def render(self, context):
...         return <div>
...             <if cond={context.prop('auth_username', None)}>
...                 Welcome back, {context.auth_username}.
...             </if>
...             <else>
...                 Hello. You need to idenfify yourself.
...             </else>
...         </div>
        
>>> print(<App />)
<div>Hello. You need to idenfify yourself.</div>

>>> who = 'John'
>>> print(
...     <AuthenticatedContext auth_username={who}>
...         <App />
...     </AuthenticatedContext>
... )
<div>Welcome back, John.</div>

>>> who = NotProvided
>>> print(
...     <AuthenticatedContext auth_username={who}>
...         <App />
...     </AuthenticatedContext>
... )
<div>Hello. You need to idenfify yourself.</div>

collectors

Provide the *Collectors classes to collect data (JS, CSS).

Available collectors: CSSCollector, JSCollector.

Usage (we'll use CSSCollector in these examples but it works the same with JSCollector):

  1. Surround the content you want to collect from with a <CSSCollector>:

    >>> print(<CSSCollector>
    ...     <Component>
    ...         <div>Foo</div>
    ...     </Component>
    ... </CSSCollector>)
    
  2. Collect things

    • Via CSSCollector.Collect

      Everything that is inside a CSSCollector.Collect tag will be collected. If it's in a component that is called many times, it will be collected each times.

      It's important to encapsulate the text to collect in a raw string or text will be html-escaped (for example > will be converted to &gt; but we really want > to be there), and content of curly braces will be interpreted as "python" (because of the way "mixt" work).

      >>> class Component(Element):
      ...     def render(self, context):
      ...         return <Fragment>
      ...             <CSSCollector.Collect>{h.Raw('''
      ... .somecontent { color: red; }
      ...             ''')}</CSSCollector.Collect>
      ...             <div class="somecontent">{self.children()}</div>
      ...         </Fragment>
      
      >>> def render():
      ...     return <body>
      ...         <CSSCollector>
      ...             <CSSCollector.Collect>{h.Raw('''
      ... * { color: black; }
      ...             ''')}</CSSCollector.Collect>
      ...             <Component>
      ...                 <div>Foo</div>
      ...             </Component>
      ...         </CSSCollector>
      ...    </body>
      

      Here the collected content will be:

      * { color: black; }
      .somecontent { color: red; }
      
    • Via the render_css method of a component

      It works like the Collect component but allows to separate css from html by moving it in a dedicated method.

      This method will be called for every component having it. And like for Collect, if a component is called many times, the output will be collected many times.

      Taking our previous example, now the Component class is simpler. Also note how we don't have to use h.Raw anymore: it's automatic.

      >>> class Component(Element):
      ...     def render_css(self, context):
      ...         return '''
      ... .somecontent { color: red; }
      ...         '''
      ...
      ...     def render(self, context):
      ...         return <div class="somecontent">{self.children()}</div>
      
    • Via the render_css_global method of a component

      It works like the render_css method but it is a class method and is called only once for each component.

      You don't have to call super in this method: the collector will collect this method for the parent classes too if any (using super would result in the content of the method in the parent class to be collected many times).

      So you can use render_css_global for global style for a component, and render_css for the style belonging to a very specific instance.

      >>> class Component(Element):
      ...     class PropTypes:
      ...         color: str
      ...
      ...     @classmethod
      ...     def render_css_global(cls, context):
      ...         return '''
      ... .somecontent { color: red; }
      ...         '''
      ...
      ...     def render_css(self, context):
      ...         if not self.has_prop("color"):
      ...             return
      ...
      ...         return '''
      ... #%(id)s { color: %(color)s; }
      ...         ''' % {'id': self.id, 'color': self.color}
      ...
      ...     def render(self, context):
      ...         return <div id={self.id} class="somecontent">{self.children()}</div>
      
  3. Display collected content

    Now that the collected collected all the content, we need a way to render it.

    • Via the render_position prop.

      The collector accept a prop named render_position which, if set, must be either "before" or "after". In this case, the content will be rendered in the tree just before the opening of the collector tag, of just after its closing tag.

      >>> def render():
      ...     return <body>
      ...         # css will be rendered here in a ``<style>`` tag.
      ...         <CSSCollector render_position="before">
      ...         # ...
      ...         </CSSCollector>
      ...     </body>
      
      >>> def render():
      ...     return <body>
      ...         <CSSCollector render_position="after">
      ...         # ...
      ...         </CSSCollector>
      ...         # css will be rendered here in a ``<style>`` tag.
      ...     </body>
      
    • Via the ref prop.

      A ref allow to get a reference of a component and use it elsewhere. See Ref to know more.

      Here, by keeping a reference to the collector we can decide where and when to render the collected content.

      • After the collector

        We'll take advantage of the possibility to pass a callable as an element in the tree.

        This callable will be called at the time of the conversion to string, so after the rendering itself.

        >>> ref = Ref()
        >>> def render():
        ...     return <body>
        ...         <CSSCollector ref={ref}>
        ...         # ...
        ...         </CSSCollector>
        ...         {ref.current.render_collected}
        ...     </body>
        
      • Before the collector

        There is a difference in using the ref before its initialization than after, because of course it doesn't exist yet. So we cannot use ref.current.render_collected because ref.current is not yet set.

        But we can still use the callable idea, with a lambda, because the lambda will be called at the end, when ref.current will be defined.

        >>> ref = Ref()
        >>> def render():
        ...     return <html>
        ...         <head>
        ...             {lambda: ref.current.render_collected()}
        ...         </head>
        ...         <body>
        ...             <CSSCollector ref={ref}>
        ...             # ...
        ...             </CSSCollector>
        ...        </body>
        ...     </html>
        
      • Outside of the tree

        You may want to extract the collected content to save it to a file, for example.

        We can use the ref for this, and pass with_tag=False to render_collected to not have the colected content surrounded by a <style> tag:

        >>> ref = Ref()
        >>> def render():
        ...     return <body>
        ...         <CSSCollector ref={ref}>
        ...         # ...
        ...         </CSSCollector>
        ...     </body>
        
        >>> save_to_file(str(render()), 'index.html')
        
        >>> css = ref.current.render_collected(with_tag=False)
        >>> save_to_file(css, 'index.css')
        
      • At different places

        We may want to save in an external file the global css, but on the file the one specific to rendered components.

        For this we can use the "namespace" feature of our collector.

        By default, all the collected content is concatenated under a namespace named "default".

        And when render_collected is used, without passing any namespace, it will render all the namespaces.

        To pass a namespace:

        • Using Collect:

          The Collect component accept a prop named namespace, which default to "default".

          >>> def render():
          ...     return <body>
          ...         <CSSCollector ref={ref}>
          ...             <CSSCollector.Collect namespace="foo">...</CSSCollector.Collect>
          ...         # ...
          ...         </CSSCollector>
          ...     </body>
          
        • Using render_css and render_css_global

          If these methods return a string, it will be collected in the "default" namespace.

          But it can render a dict, the keys being the namespaces to use. The advantage is to be able to fill many namespaces at once.

          In the following example, we tell to use the "file" namespace (it's just a string, you can use what you want) for the global css, and keep the default namespace for the css specific to this instance.

          >>> class Component(Element):
          ...     class PropTypes:
          ...         color: str
          ...
          ...     @classmethod
          ...     def render_css_global(cls, context):
          ...         return {
          ...            "file": '''
          ... .somecontent { color: red; }
          ...            '''
          ...         }
          ...
          ...     def render_css(self, context):
          ...         if not self.has_prop("color"):
          ...             return
          ...
          ...         return '''
          ... #%(id)s { color: %(color)s; }
          ...         ''' % {'id': self.id, 'color': self.color}
          ...
          ...     def render(self, context):
          ...         return <div id={self.id} class="somecontent">{self.children()}</div>
          

        And now to render our html and our css, we can pass namespaces to the render_collected method:

        >>> ref = Ref()
        >>> def render():
        ...     return <html>
        ...         <head>
        ...             {lambda: ref.current.render_collected("default")}
        ...         </head>
        ...         <body>
        ...             <CSSCollector ref={ref}>
        ...             # ...
        ...             </CSSCollector>
        ...        </body>
        ...     </html>
        
        >>> save_to_file(str(render()), 'index.html')
        
        # here "outside" is an empty (not defined) namespace but it still work
        >>> css = ref.current.render_collected("file", "outside", with_tag=False)
        >>> save_to_file(css, 'index.css')
        

        And if we want to generate many html files and be sure the external css file will have everything that is needed, we can use the reuse feature.

        It tells a collector to reuse another collector for some content. By default it's all the content, but it can be limited to global or non-global content, and it can also be limited to some namespaces only.

        >>> global_collector = CSSCollector()
        
        >>> ref = Ref()
        >>> def render(content):
        ...     return <html>
        ...         <head>
        ...             {lambda: ref.current.render_collected("default")}
        ...         </head>
        ...         <body>
        ...             <CSSCollector
        ...               ref={ref}
        ...               reuse={global_collector}
        ...               reuse_global=True  # the default
        ...               reuse_non_global=False
        ...               reuse_namespaces=None  # the default, else can be a list of namespaces
        ...             >
        ...             {content}
        ...             </CSSCollector>
        ...        </body>
        ...     </html>
        
        # each file will have its own non-global styles
        >>> save_to_file(str(render("page 1")), 'page1.html')
        >>> save_to_file(str(render("page 2")), 'page2.html')
        
        # we'll have the global styles for every components used on each page
        # useful if one component used on page 2 but not on page 1 for example
        >>> css = global_collector.render_collected(with_tag=False)
        >>> save_to_file(css, 'index.css')
        

Note: you can use mixt.contrib.css with the CSS collector. See Related documentation.

Classes

CSSCollector

A collector that'll surround collected content in a <style> tag in render_collected.

The particularities of CSSCollector:

  • a CSSCollector.Collect component

  • render_css_global class methods are collected once

  • render_css methods are collected for every component

  • the default namespace is "default"

You can use mixt.contrib.css with the CSS collector. See Related documentation.

PropTypes

PropTypes for the CSSCollector component.

ref: Ref

A reference to the element itself that can be used later. See Ref for more information.

id: str

The id of the element. It will not be passed down the tree like _class.

_class: str

A string containing the "class" html attribute that will be passed down to the first rendered html element.

render_position: DefaultChoices = [None, 'before', 'after']

Tell where to insert the collected content.

If set, the collected content will be inserted before opening tag of the collector or after its closing tag.

If not set, the content won't be inserted: the render_collected method will need to be called to get the content. For example using the ref prop.

reuse: Any

Tell the collector to use data from the given collector. Useful to collect from many components not in the same tree and extract collected content for all at once.

reuse_global: bool = True

If True (the default) and if reuse is set, the globally collected stuff will be collected by the reused collector.

reuse_non_global: bool = True

If True (the default) and if reuse is set, the non-globally collected stuff will be collected by the reused collector.

reuse_namespaces: List[str]

If not None (the default), only the given namespaces will be collected by the reuse, the other being collected by self.. Else (if None), all namespaces will be collected by reuse.

type: str = 'text/css'

The value of the type attribute of the style tag that will be generated.

JSCollector

A collector that'll surround collected content in a <script> tag in render_collected.

The particularities of JSCollector:

  • a JSCollector.Collect component

  • render_js_global class methods are collected once

  • render_js methods are collected for every component

  • the default namespace is "default"

PropTypes

PropTypes for the JSCollector component.

ref: Ref

A reference to the element itself that can be used later. See Ref for more information.

id: str

The id of the element. It will not be passed down the tree like _class.

_class: str

A string containing the "class" html attribute that will be passed down to the first rendered html element.

render_position: DefaultChoices = [None, 'before', 'after']

Tell where to insert the collected content.

If set, the collected content will be inserted before opening tag of the collector or after its closing tag.

If not set, the content won't be inserted: the render_collected method will need to be called to get the content. For example using the ref prop.

reuse: Any

Tell the collector to use data from the given collector. Useful to collect from many components not in the same tree and extract collected content for all at once.

reuse_global: bool = True

If True (the default) and if reuse is set, the globally collected stuff will be collected by the reused collector.

reuse_non_global: bool = True

If True (the default) and if reuse is set, the non-globally collected stuff will be collected by the reused collector.

reuse_namespaces: List[str]

If not None (the default), only the given namespaces will be collected by the reuse, the other being collected by self.. Else (if None), all namespaces will be collected by reuse.

type: str = 'text/javascript'

The value of the type attribute of the script tag that will be generated.

HTML tags

All available HTML tags, with their props.

We support only actual (and not deprecated) tags in the HTML5 spec, with all their - not deprecated - attributes.

All tags in this html module must be used in lowercase in "mixt" mode. For example html.A is used like this: <a>.

To use in "mixt" mode, a file must import html from mixt.

There is also a shortcut: from mixt import h to use directly. But still, for "mixt" mode, importing html is mandatory.

All props of type bool are considered False by default, in the sense of HTML: the prop is not passed to the tag. But using el.bool_prop or el.prop("bool_prop") won't work if not specifically set. Use el.prop("bool_prop", False) if you need to access such a prop from a parent component.

_Base

Base for all HTML tags, with common props.

Accept children: no

PropTypes

ref: Ref

A reference to the element itself that can be used later. See Ref for more information.

id: str
_class: str

A string containing the "class" html attribute that will be passed down to the first rendered html element.

accesskey: str
autocapitalize: Choices = ['sentences', 'none', 'words', 'characters']
contenteditable: Choices = ['false', 'true']
contextmenu: str
dir: Choices = ['auto', 'ltr', 'rtl']
draggable: Choices = ['false', 'true']
dropzone: str
hidden: bool
itemid: str
itemprop: str
itemscope: bool
itemstype: str
lang: str
slot: str
spellcheck: bool
style: str
tabindex: int
title: str
translate: Choices = ['', 'yes', 'no']
onabort: str
onautocomplete: str
onautocompleteerror: str
onblur: str
oncancel: str
oncanplay: str
oncanplaythrough: str
onchange: str
onclick: str
onclose: str
oncontextmenu: str
oncuechange: str
ondblclick: str
ondrag: str
ondragend: str
ondragenter: str
ondragexit: str
ondragleave: str
ondragover: str
ondragstart: str
ondrop: str
ondurationchange: str
onemptied: str
onended: str
onerror: str
onfocus: str
oninput: str
oninvalid: str
onkeydown: str
onkeypress: str
onkeyup: str
onload: str
onloadeddata: str
onloadedmetadata: str
onloadstart: str
onmousedown: str
onmouseenter: str
onmouseleave: str
onmousemove: str
onmouseout: str
onmouseover: str
onmouseup: str
onmousewheel: str
onpause: str
onplay: str
onplaying: str
onprogress: str
onratechange: str
onreset: str
onresize: str
onscroll: str
onseeked: str
onseeking: str
onselect: str
onshow: str
onsort: str
onstalled: str
onsubmit: str
onsuspend: str
ontimeupdate: str
ontoggle: str
onvolumechange: str
onwaiting: str

A

Implement the a HTML tag.

Bases: _Hyperlink

Accept children: yes

PropTypes

role: Choices = ['button', 'checkbox', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'switch', 'tab', 'treeitem']
ping: str
type: str

Abbr

Implement the abbr HTML tag.

Accept children: yes

Address

Implement the address HTML tag.

Accept children: yes

Area

Implement the area HTML tag.

Bases: _Hyperlink

Accept children: yes

PropTypes

alt: str
coords: str
media: str
shape: Choices = ['rect', 'poly', 'default']

Article

Implement the article HTML tag.

Accept children: yes

PropTypes

role: Choices = ['application', 'document', 'feed', 'main', 'presentation', 'region']

Aside

Implement the aside HTML tag.

Accept children: yes

PropTypes

role: Choices = ['feed', 'note', 'presentation', 'region', 'search']

_Media

Base for Audio and Video elements.

Accept children: yes

PropTypes

role: Choices = ['application']
autoplay: bool
controls: bool
crossorigin: Choices = ['', 'anonymous', 'use-credentials']
loop: bool
muted: bool
preload: Choices = ['', 'auto', 'none', 'metadata']
src: str

Audio

Implement the audio HTML tag.

Bases: _Media

Accept children: yes

B

Implement the b HTML tag.

Accept children: yes

PropTypes

role: str

Base

Implement the base HTML tag.

Accept children: no

PropTypes

href: str
target: str

Bdi

Implement the bdi HTML tag.

Accept children: yes

PropTypes

role: str

Bdo

Implement the bdo HTML tag.

Accept children: yes

PropTypes

role: str

Blockquote

Implement the blockquote HTML tag.

Accept children: yes

PropTypes

role: str
cite: str

Body

Implement the body HTML tag.

Accept children: yes

PropTypes

onafterprint: str
onbeforeprint: str
onbeforeunload: str
onhashchange: str
onlanguagechange: str
onmessage: str
onoffline: str
ononline: str
onpopstate: str
onredo: str
onstorage: str
onundo: str
onunload: str

Br

Implement the br HTML tag.

Accept children: no

PropTypes

role: str

Button

Implement the button HTML tag.

Accept children: yes

PropTypes

role: Choices = ['checkbox', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'radio', 'switch', 'tab']
autofocus: bool
autocomplete: Choices = ['off']
disabled: bool
form: str
formaction: str
formenctype: Choices = ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain']
formmethod: Choices = ['get', 'post']
formnovalidate: bool
formtarget: str
name: str
type: Choices = ['submit', 'reset', 'button']
value: Any

Canvas

Implement the canvas HTML tag.

Accept children: yes

PropTypes

role: str
height: Union[int, float]
width: Union[int, float]

Caption

Implement the caption HTML tag.

Accept children: yes

Cite

Implement the cite HTML tag.

Accept children: yes

PropTypes

role: str

Code

Implement the code HTML tag.

Accept children: yes

PropTypes

role: str

Col

Implement the col HTML tag.

Accept children: no

PropTypes

span: int

Colgroup

Implement the colgroup HTML tag.

Accept children: yes

PropTypes

span: int

Data

Implement the data HTML tag.

Accept children: yes

PropTypes

value: str

Datalist

Implement the datalist HTML tag.

Accept children: yes

Dd

Implement the dd HTML tag.

Accept children: yes

Del

Implement the del HTML tag.

Accept children: yes

PropTypes

role: str
cite: str
datetime: str

Details

Implement the details HTML tag.

Accept children: yes

PropTypes

open: bool

Dfn

Implement the dfn HTML tag.

Accept children: yes

PropTypes

role: str

Div

Implement the div HTML tag.

Accept children: yes

PropTypes

role: str

Dl

Implement the dl HTML tag.

Accept children: yes

PropTypes

role: Choices = ['group', 'presentation']

Dt

Implement the dt HTML tag.

Accept children: yes

Em

Implement the em HTML tag.

Accept children: yes

PropTypes

role: str

Embed

Implement the embed HTML tag.

Accept children: yes

PropTypes

role: Choices = ['application', 'document', 'img', 'presentation']
height: Union[int, float]
src: str
type: str
widht: str

Fieldset

Implement the fieldset HTML tag.

Accept children: yes

PropTypes

role: Choices = ['group', 'presentation']
disabled: bool
form: str
name: str

Figcaption

Implement the figcaption HTML tag.

Accept children: yes

PropTypes

role: Choices = ['group', 'presentation']

Figure

Implement the figure HTML tag.

Accept children: yes

PropTypes

role: Choices = ['group', 'presentation']

Form

Implement the form HTML tag.

Accept children: yes

PropTypes

role: Choices = ['group', 'presentation']
accept_charset: str
action: str
autocomplete: Choices = ['on', 'off']
enctype: Choices = ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain']
method: Choices = ['get', 'post']
name: str
target: str

H

Can replace H* tags by passing a level prop.

Accept children: yes

PropTypes

role: Choices = ['tab', 'presentation']
level: Required[Choices] = [1, 2, 3, 4, 5, 6]

H1

Implement the h1 HTML tag.

Bases: _H

Accept children: yes

H2

Implement the h2 HTML tag.

Bases: _H

Accept children: yes

H3

Implement the h3 HTML tag.

Bases: _H

Accept children: yes

H4

Implement the h4 HTML tag.

Bases: _H

Accept children: yes

H5

Implement the h5 HTML tag.

Bases: _H

Accept children: yes

H6

Implement the h6 HTML tag.

Bases: _H

Accept children: yes

Head

Implement the head HTML tag.

Accept children: yes

Header

Implement the header HTML tag.

Accept children: yes

PropTypes

role: Choices = ['group', 'presentation']

Hr

Implement the hr HTML tag.

Accept children: no

PropTypes

role: Choices = ['presentation']

Html

Implement the html HTML tag.

Accept children: yes

PropTypes

xmlns: str
xmlns__og: str
xmlns__fb: str

I

Implement the i HTML tag.

Accept children: yes

PropTypes

role: str

Iframe

Implement the iframe HTML tag.

Accept children: yes

PropTypes

role: Choices = ['application', 'document', 'img']
allowfullscreen: bool
allowpaymentrequest: bool
height: Union[int, float]
name: str
referrerpolicy: Choices = ['no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url']
sandbox: str
src: str
srcdoc: str
width: Union[int, float]

Img

Implement the img HTML tag.

Accept children: no

PropTypes

role: str
alt: str
crossorigin: Choices = ['', 'anonymous', 'use-credentials']
decoding: Choices = ['sync', 'async', 'auto']
height: Union[int, float]
ismap: bool
referrerpolicy: Choices = ['no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url']
sizes: str
src: str
srcset: str
width: Union[int, float]
usemap: str

Input

Implement the input HTML tag.

The props defined in this class are the one available for each input types. Each type has its own class, InputXXX, defining their own props.

Accept children: no

PropTypes

type: Choices = ['button', 'checkbox', 'color', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month', 'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time', 'url', 'week']
autocomplete: Choices = ['off', 'on', 'name', 'honorific-prefix', 'given-name', 'additional-name', 'family-name', 'honorific-suffix', 'nickname', 'email', 'username', 'new-password', 'current-password', 'organization-title', 'organization', 'street-address', 'address-line1', 'address-line2', 'address-line3', 'address-level4', 'address-level3', 'address-level2', 'address-level1', 'country', 'country-name', 'postal-code', 'cc-name', 'cc-given-name', 'cc-additional-name', 'cc-family-name', 'cc-number', 'cc-exp', 'cc-exp-month', 'cc-exp-year', 'cc-csc', 'cc-type', 'transaction-currency', 'transaction-amount', 'language', 'bday', 'bday-day', 'bday-month', 'bday-year', 'sex', 'tel', 'tel-country-code', 'tel-national', 'tel-area-code', 'tel-local', 'tel-local-prefix', 'tel-local-suffix', 'tel-extension', 'url', 'photo']
autofocus: bool
disabled: bool
form: str
formaction: str
formenctype: Choices = ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain']
formmethod: Choices = ['get', 'post']
formnovalidate: bool
formtarget: str
_list: str
name: str

_KeyboardInput

Base for input types meant to be filled via keyboard.

Bases: Input

Accept children: no

PropTypes

inputmode: Choices = ['none, text, decimal, numeric, tel, search, email, url']
minlength: int
maxlength: int
pattern: str
placeholder: str
readonly: bool
required: bool
size: int
value: str

InputButton

Implement the input type='button' HTML tag.

Bases: Input

Accept children: no

PropTypes

role: Choices = ['link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'radio', 'switch', 'tab']

InputCheckbox

Implement the input type='checkbox' HTML tag.

Bases: Input

Accept children: no

PropTypes

role: Choices = ['button', 'menuitemcheckbox', 'option', 'switch']
checked: bool
required: bool

InputImage

Implement the input type='image' HTML tag.

Bases: Input

Accept children: no

PropTypes

role: Choices = ['link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'radio', 'switch']
height: Union[int, float]
src: str
width: Union[int, float]

InputRadio

Implement the input type='radio' HTML tag.

Bases: Input

Accept children: no

PropTypes

role: Choices = ['menuitemradio']
checked: bool
required: bool

InputColor

Implement the input type='color' HTML tag.

Bases: Input

Accept children: no

PropTypes

required: bool

InputDate

Implement the input type='date' HTML tag.

Bases: Input

Accept children: no

PropTypes

min: str
max: str
readonly: bool
required: bool
step: Union[str, int, float]

InputDateTimeLocal

Implement the input type='datetime' HTML tag.

Bases: Input

Accept children: no

PropTypes

min: str
max: str
readonly: bool
required: bool
step: Union[str, int, float]

InputEmail

Implement the input type='email' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

PropTypes

multiple: bool

InputFile

Implement the input type='file' HTML tag.

Bases: Input

Accept children: no

PropTypes

accept: str
capture: bool
multiple: bool
required: bool

InputHidden

Implement the input type='hidden' HTML tag.

Bases: Input

Accept children: no

InputMonth

Implement the input type='month' HTML tag.

Bases: Input

Accept children: no

PropTypes

readonly: bool
required: bool

InputNumber

Implement the input type='number' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

PropTypes

min: Union[int, float]
max: Union[int, float]
step: Union[str, int, float]

InputPassword

Implement the input type='password' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

InputRange

Implement the input type='range' HTML tag.

Bases: Input

Accept children: no

PropTypes

required: bool

InputReset

Implement the input type='reset' HTML tag.

Bases: Input

Accept children: no

InputSearch

Implement the input type='search' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

InputSubmit

Implement the input type='submit' HTML tag.

Bases: Input

Accept children: no

InputTel

Implement the input type='tel' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

InputText

Implement the input type='text' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

InputUrl

Implement the input type='url' HTML tag.

Bases: _KeyboardInput, Input

Accept children: no

InputWeek

Implement the input type='week' HTML tag.

Bases: Input

Accept children: no

PropTypes

readonly: bool
required: bool

Ins

Implement the ins HTML tag.

Accept children: yes

PropTypes

role: str
cite: str
datetime: str

Kbd

Implement the kbd HTML tag.

Accept children: yes

PropTypes

role: str

Label

Implement the label HTML tag.

Accept children: yes

PropTypes

_for: str
form: str

Legend

Implement the legend HTML tag.

Accept children: yes

Li

Implement the li HTML tag.

Accept children: yes

PropTypes

role: Choices = ['menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'presentation', 'radio', 'separator', 'tab', 'treeitem']
value: int

Main

Implement the main HTML tag.

Accept children: yes

PropTypes

role: Choices = ['main', 'presentation']

Map

Implement the map HTML tag.

Accept children: yes

PropTypes

name: str

Mark

Implement the mark HTML tag.

Accept children: yes

PropTypes

role: str

Meta

Implement the meta HTML tag.

Accept children: no

PropTypes

charset: str
content: str
http_equiv: Choices = ['content-security-policy', 'refresh']
name: Choices = ['application-name', 'author', 'description', 'generator', 'keywords', 'referrer', 'creator', 'googlebot', 'publisher', 'robots', 'slurp', 'viewport']

Meter

Implement the meter HTML tag.

Accept children: yes

PropTypes

value: Union[int, float]
min: Union[int, float]
max: Union[int, float]
low: Union[int, float]
high: Union[int, float]
optimum: Union[int, float]
form: str

Nav

Implement the nav HTML tag.

Accept children: yes

Noscript

Implement the noscript HTML tag.

Accept children: yes

Object

Implement the object HTML tag.

Accept children: yes

PropTypes

role: Choices = ['application', 'document', 'image']
data: str
form: str
height: Union[int, float]
name: str
type: str
typemustmatch: bool
usemap: str
width: Union[int, float]

Ol

Implement the ol HTML tag.

Accept children: yes

PropTypes

role: Choices = ['directory', 'group', 'listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'toolbar', 'tree', 'presentation']
reversed: bool
start: int
type: Choices = ['1', 'a', 'A', 'i', 'I']

Optgroup

Implement the optgroup HTML tag.

Accept children: yes

PropTypes

disabled: bool
label: str

Option

Implement the option HTML tag.

Accept children: yes

PropTypes

disabled: bool
label: str
selected: bool
value: str

Output

Implement the output HTML tag.

Accept children: yes

PropTypes

role: str
_for: str
form: str
name: str

P

Implement the p HTML tag.

Accept children: yes

PropTypes

role: str

Param

Implement the param HTML tag.

Accept children: yes

PropTypes

name: str
value: str

Picture

Implement the picture HTML tag.

Accept children: yes

Pre

Implement the pre HTML tag.

Accept children: yes

PropTypes

role: str

Progress

Implement the progress HTML tag.

Accept children: yes

PropTypes

max: Union[int, float]
value: Union[int, float]

Q

Implement the q HTML tag.

Accept children: yes

PropTypes

role: str
cite: str

Rp

Implement the rp HTML tag.

Accept children: yes

PropTypes

role: str

Rt

Implement the rt HTML tag.

Accept children: yes

PropTypes

role: str

Rtc

Implement the rtc HTML tag.

Accept children: yes

PropTypes

role: str

Ruby

Implement the ruby HTML tag.

Accept children: yes

PropTypes

role: str

S

Implement the s HTML tag.

Accept children: yes

PropTypes

role: str

Samp

Implement the samp HTML tag.

Accept children: yes

PropTypes

role: str

Script

Implement the script HTML tag.

Accept children: yes

PropTypes

_async: bool
crossorigin: Choices = ['', 'anonymous', 'use-credentials']
defer: bool
integrity: str
nomodule: bool
nonce: str
src: str
type: str

Section

Implement the section HTML tag.

Accept children: yes

PropTypes

role: Choices = ['alert', 'alertdialog', 'application', 'banner', 'complementary', 'contentinfo', 'dialog', 'document', 'feed', 'log', 'main', 'marquee', 'navigation', 'search', 'status', 'tabpanel']

Select

Implement the select HTML tag.

Accept children: yes

PropTypes

role: Choices = ['menu']
autofocus: bool
disabled: bool
form: str
multiple: bool
name: str
required: bool
size: int

Slot

Implement the slot HTML tag.

Accept children: yes

PropTypes

name: str

Source

Implement the source HTML tag.

Accept children: no

PropTypes

sizes: str
src: str
srccet: str
type: str
media: str

Span

Implement the span HTML tag.

Accept children: yes

PropTypes

role: str

Strong

Implement the strong HTML tag.

Accept children: yes

PropTypes

role: str

Style

Implement the style HTML tag.

Accept children: yes

PropTypes

media: str
nonce: str
type: str

Sub

Implement the sub HTML tag.

Accept children: yes

PropTypes

role: str

Summary

Implement the summary HTML tag.

Accept children: yes

PropTypes

role: Choices = ['button']

Sup

Implement the sup HTML tag.

Accept children: yes

PropTypes

role: str

Table

Implement the table HTML tag.

Accept children: yes

PropTypes

role: str

Tbody

Implement the tbody HTML tag.

Accept children: yes

PropTypes

role: str

Td

Implement the td HTML tag.

Accept children: yes

PropTypes

role: str
colspan: int
headers: str
rowspan: int

Template

Implement the template HTML tag.

Accept children: yes

Textarea

Implement the textarea HTML tag.

Accept children: yes

PropTypes

autocomplete: Choices = ['on', 'off']
autofocus: bool
cols: int
disabled: bool
form: str
maxlength: int
minlength: int
name: str
placeholder: str
readonly: bool
required: bool
wrap: Choices = ['soft', 'hard', 'off']

Tfoot

Implement the tfoot HTML tag.

Accept children: yes

PropTypes

role: str

Th

Implement the th HTML tag.

Accept children: yes

PropTypes

role: str
abbr: str
colspan: int
headers: str
rowspan: int
scope: Choices = ['row', 'col', 'rowgroup', 'colgroup', 'auto']

Thead

Implement the thead HTML tag.

Accept children: yes

PropTypes

role: str

Time

Implement the time HTML tag.

Accept children: yes

PropTypes

role: str
datetime: str

Title

Implement the title HTML tag.

Accept children: yes

Tr

Implement the tr HTML tag.

Accept children: yes

PropTypes

role: str

Track

Implement the track HTML tag.

Accept children: no

PropTypes

default: bool
kind: Choices = ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata']
label: str
src: str
srclang: str

U

Implement the u HTML tag.

Accept children: yes

PropTypes

role: str

Ul

Implement the ul HTML tag.

Accept children: yes

PropTypes

role: Choices = ['directory', 'group', 'listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'toolbar', 'tree', 'presentation']

Var

Implement the var HTML tag.

Accept children: yes

PropTypes

role: str

Video

Implement the video HTML tag.

Bases: _Media

Accept children: yes

PropTypes

height: Union[int, float]
poster: str
width: Union[int, float]
playsinline: bool

Wbr

Implement the wbr HTML tag.

Accept children: yes

PropTypes

role: str

HTML utils

RawHtml

Element to handle raw text in html.

The rule to know when some text will be automatically escaped or not is simple:

  • if it's python: it will be escaped

  • if it's "mixt": it will not

RawHtml helps to tell mixt to not escape some text. It's a component with a text prop that is generally used via the Raw function that take some text as an unnamed argument that is passed to the text prop of a new RawHtml component.

So calling html.Raw("some text") is sugar for calling html.RawHtml(text="some text).

Generally you should not have to worry, mixt does its best to handle things for you.

But for example, when rendering some JS or CSS, you really want RAW, without escaping.

Below are some examples to show when text is escaped or not.

PropTypes

PropTypes for the RawHtml component.

text: str

The text that will be rendered without escaping.

Example

>>> from mixt import h, html  # same but ``html`` for mixt mode, and ``h`` as a shortcut

# Simple rendered text will be escaped. Because it's seen as python
>>> class Component(Element):
...     def render(self, context):
...         return 'Hello "world" !'

>>> print(<Component />)
Hello &quot;world&quot; !

# If we don't want this, we need to mark the text as raw.
>>> class Component(Element):
...     def render(self, context):
...         return h.Raw('Hello "world" !')

>>> print(<Component />)
Hello "world" !

# In "mixt" mode, text will NOT be escaped.
# Because calling ``<div>text</div>`` is in fact calling ``html.Div()(html.Raw('text'))``
>>> class Component(Element):
...     def render(self, context):
        return <div>Hello "world" !</Div>"hello

>>> print(<Component />)
<div>Hello "world" !</div>

# But it will be in attributes:
>>> class Component(Element):
...     def render(self, context):
        return <div data-foo="<bar>">Hello "world" !</div>

>>> print(<Component />)
<div data-foo="&lt;bar&gt;">Hello "world" !</div>

# Even if given as a python string
>>> class Component(Element):
...     def render(self, context):
...         return <div data-foo={"<bar>"}>Hello "world" !</div>

>>> print(<Component />)
<div data-foo="&lt;bar&gt;">Hello "world" !</div>

# Text in python mode, will be escaped:
>>> class Component(Element):
...     def render(self, context):
...         return h.Fragment()('Hello "world" !')

>>> print(<Component />)
<div>Hello &quot;world&quot; !</div>

# Use ``RawHtml`` to solve this.
>>> class Component(Element):
...     def render(self, context):
...         return h.Div()(h.Raw('Hello "world" !'))

>>> print(<Component />)
<div>Hello "world" !</div>

Raw(text: str) → RawHtml

Help to easily construct a RawHtml element.

Details

See RawHtml for more information.

Arguments

text: str

The text to pass as a prop to the RawHtml element to construct.

Returns

RawHtml

The newly constructed element.

Fragment

An invisible tag that is used to hold many other tags.

Example

>>> class Component(Element):
    ...     def render(self, context):
    ...         return <Fragment>
    ...             <div>Foo</div>
    ...             <div>Bar</div>
    ...         </Fragment>

    >>> print(<Component />)
    <div>Foo</div><div>Bar</div>

if / else tags

Mixt avoids support for logic within the HTML flow, except for one case where we found it especially useful: conditionally rendering HTML.

That is why Mixt provides the <if> tag, which takes a prop named cond.

Children of an <if> tag are only rendered if cond evaluates to True.

It comes with the <else> tag, not taking any prop, that is optional but if used, must come right after the closing </if> tag.

Children of an <else> tag are only rendered if the cond prop of the <if> tag evaluates to False.

Example

>>> class Component(Element):
...     class PropTypes:
...         flag: Required[bool]
...
...     def render(self, context):
...         return <div>
...             <if cond={self.flag}>
...                 <span>It's TRUE</span>
...             </if>
...             <else>
...                 <p>It's FALSE</p>
...             </else>
...         </div>

>>> print(<Component flag=True />)
<div><span>It's TRUE</span></div>

>>> print(<Component flag=True />)
<div><p>It's FALSE</p></div>

# A more pythonic way to do this without using these if/else tags:

>>> class Component(Element):
>>>     def render(self, context):
... 
...         if self.flag:
...             conditional_render =  <span>It's TRUE</span>
...         else:
...             conditional_render =  <p>It's FALSE</p>
...
...         return <div>
...             {conditional_render}
...         </div>

# Or using the fact that ``None`` is not rendered:

>>>     def render(self, context):
...
...         part_if_true = part_if_false = None
...
...         if self.flag:
...             part_if_true =  <span>It's TRUE</span>
...         else:
...             part_if_false =  <p>It's FALSE</p>
...
...         return <div>
...             {part_if_true}
...             {part_if_false}
...         </div>

Comments

HTML and python comments are correctly handled but not rendered in the final HTLM.

Example

>>> class Component(Element):
...     def render(self, context):
...         return <div>
...             <!-- inside the div -->
...             Foo  # bar?
...         </div>

>>> print(<Component />)
<div>Foo</div>

Doctype

Implement HTML doctype declaration.

PropTypes

PropTypes for the Doctype element.

doctype: str = 'html'

The doctype to use. Default to html.

Example

# It can be used as a normal HTML doctype:

>>> class Component(Element):
...     def render(self, context):
...         return <!DOCTYPE html>

>>> print(<Component />)
<!DOCTYPE html>

# Or using it as a component:

>>> class Component(Element):
...     def render(self, context):
...         return <Doctype doctype=html />

>>> print(<Component />)
<!DOCTYPE html>

# Or even better, taking advantage of the default value of the ``doctype`` prop:

>>> class Component(Element):
...     def render(self, context):
...         return <Doctype />

>>> print(<Component />)
<!DOCTYPE html>

exceptions

All mixt exceptions.

Each type of error has its own exception, but there is a tree of exception classes starting from MixtException, so it's easy to catch many exception types at one.

This module can be imported from mixt: from mixt import exceptions.

Classes

MixtException

Default exception raised for all Mixt problems.

Base: Exception.

ElementError

Exception related to element classes.

Base: MixtException.

PropError

Exception related to props.

Base: ElementError.

PropTypeError

Exception related to prop-types definition.

Base: PropError.

PropTypeChoicesError

Exception related to prop-types definition for type "choices".

Base: PropTypeError.

PropTypeRequiredError

Exception related to prop-types definition for required props.

Base: PropTypeError.

InvalidPropNameError

Exception raised when a name is not in allowed props.

Bases: PropError, AttributeError.

InvalidPropValueError

Exception raised when a value is not valid for a prop.

Bases: PropError, TypeError.

InvalidPropChoiceError

Exception raised when a value is not valid for a prop of type "choices".

Base: InvalidPropValueError.

InvalidPropBoolError

Exception raised when a value is not valid for a prop of type "bool".

Base: InvalidPropValueError.

RequiredPropError

Exception raised when a prop is required but not set.

Bases: PropError, TypeError.

UnsetPropError

Exception raised when a prop is accessed but not set (without default).

Bases: PropError, AttributeError.

InvalidChildrenError

Exception related to children of an element.

Base: ElementError.

GeneralParserError

Exception related to parsing mixt-encoded python/html.

Base: Exception.

BadCharError

Exception raised by the parser when an unexpected character is found.

Base: ParserStateError.

ParserError

Exception raised by the mixt parser, with position of the problem.

Base: GeneralParserError.