Skip to content

API¤

Component ¤

Component(
    registered_name: Optional[str] = None,
    component_id: Optional[str] = None,
    outer_context: Optional[Context] = None,
    registry: Optional[ComponentRegistry] = None,
)

Methods:

Attributes:

Media class-attribute instance-attribute ¤

Media = ComponentMediaInput

See source code

Defines JS and CSS media files associated with this component.

View class-attribute instance-attribute ¤

component_id instance-attribute ¤

component_id = component_id or gen_id()

css class-attribute instance-attribute ¤

css: Optional[str] = None

See source code

Inlined CSS associated with this component.

input property ¤

input: RenderInput[ArgsType, KwargsType, SlotsType]

See source code

Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render method.

is_filled property ¤

is_filled: SlotIsFilled

See source code

Dictionary describing which slots have or have not been filled.

This attribute is available for use only within the template as {{ component_vars.is_filled.slot_name }}, and within on_render_before and on_render_after hooks.

js class-attribute instance-attribute ¤

js: Optional[str] = None

See source code

Inlined JS associated with this component.

media instance-attribute ¤

media: Media

See source code

Normalized definition of JS and CSS media files associated with this component.

NOTE: This field is generated from Component.Media class.

media_class class-attribute instance-attribute ¤

media_class: Media = Media

name property ¤

name: str

outer_context instance-attribute ¤

outer_context: Context = outer_context or Context()

registered_name instance-attribute ¤

registered_name: Optional[str] = registered_name

registry instance-attribute ¤

registry = registry or registry

response_class class-attribute instance-attribute ¤

response_class = HttpResponse

See source code

This allows to configure what class is used to generate response from render_to_response

template class-attribute instance-attribute ¤

template: Optional[Union[str, Template]] = None

See source code

Inlined Django template associated with this component. Can be a plain string or a Template instance.

Only one of template_name, get_template_name, template or get_template must be defined.

template_name class-attribute instance-attribute ¤

template_name: Optional[str] = None

See source code

Filepath to the Django template associated with this component.

The filepath must be relative to either the file where the component class was defined, or one of the roots of STATIFILES_DIRS.

Only one of template_name, get_template_name, template or get_template must be defined.

as_view classmethod ¤

as_view(**initkwargs: Any) -> ViewFn

See source code

Shortcut for calling Component.View.as_view and passing component instance to it.

get_context_data ¤

get_context_data(*args: Any, **kwargs: Any) -> DataType

get_template ¤

get_template(context: Context) -> Optional[Union[str, Template]]

See source code

Inlined Django template associated with this component. Can be a plain string or a Template instance.

Only one of template_name, get_template_name, template or get_template must be defined.

get_template_name ¤

get_template_name(context: Context) -> Optional[str]

See source code

Filepath to the Django template associated with this component.

The filepath must be relative to either the file where the component class was defined, or one of the roots of STATIFILES_DIRS.

Only one of template_name, get_template_name, template or get_template must be defined.

inject ¤

inject(key: str, default: Optional[Any] = None) -> Any

See source code

Use this method to retrieve the data that was passed to a {% provide %} tag with the corresponding key.

To retrieve the data, inject() must be called inside a component that's inside the {% provide %} tag.

You may also pass a default that will be used if the provide tag with given key was NOT found.

This method mut be used inside the get_context_data() method and raises an error if called elsewhere.

Example:

Given this template:

{% provide "provider" hello="world" %}
    {% component "my_comp" %}
    {% endcomponent %}
{% endprovide %}

And given this definition of "my_comp" component:

from django_components import Component, register

@register("my_comp")
class MyComp(Component):
    template = "hi {{ data.hello }}!"
    def get_context_data(self):
        data = self.inject("provider")
        return {"data": data}

This renders into:

hi world!

As the {{ data.hello }} is taken from the "provider".

on_render_after ¤

on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]

See source code

Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.

You can use this hook to access the context or the template, but modifying them won't have any effect.

To override the content that gets rendered, you can return a string or SafeString from this hook.

on_render_before ¤

on_render_before(context: Context, template: Template) -> None

See source code

Hook that runs just before the component's template is rendered.

You can use this hook to access or modify the context or the template.

render classmethod ¤

render(
    context: Optional[Union[Dict[str, Any], Context]] = None,
    args: Optional[ArgsType] = None,
    kwargs: Optional[KwargsType] = None,
    slots: Optional[SlotsType] = None,
    escape_slots_content: bool = True,
    type: RenderType = "document",
    render_dependencies: bool = True,
    request: Optional[HttpRequest] = None,
) -> str

See source code

Render the component into a string.

Inputs: - args - Positional args for the component. This is the same as calling the component as {% component "my_comp" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component "my_comp" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - "document" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - render_dependencies - Set this to False if you want to insert the resulting HTML into another component. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context Example:

MyComponent.render(
    args=[1, "two", {}],
    kwargs={
        "key": 123,
    },
    slots={
        "header": 'STATIC TEXT HERE',
        "footer": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',
    },
    escape_slots_content=False,
)

render_to_response classmethod ¤

render_to_response(
    context: Optional[Union[Dict[str, Any], Context]] = None,
    slots: Optional[SlotsType] = None,
    escape_slots_content: bool = True,
    args: Optional[ArgsType] = None,
    kwargs: Optional[KwargsType] = None,
    type: RenderType = "document",
    request: Optional[HttpRequest] = None,
    *response_args: Any,
    **response_kwargs: Any
) -> HttpResponse

See source code

Render the component and wrap the content in the response class.

The response class is taken from Component.response_class. Defaults to django.http.HttpResponse.

This is the interface for the django.views.View class which allows us to use components as Django views with component.as_view().

Inputs: - args - Positional args for the component. This is the same as calling the component as {% component "my_comp" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component "my_comp" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - "document" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context

Any additional args and kwargs are passed to the response_class.

Example:

MyComponent.render_to_response(
    args=[1, "two", {}],
    kwargs={
        "key": 123,
    },
    slots={
        "header": 'STATIC TEXT HERE',
        "footer": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',
    },
    escape_slots_content=False,
    # HttpResponse input
    status=201,
    headers={...},
)
# HttpResponse(content=..., status=201, headers=...)

ComponentFileEntry ¤

Bases: tuple

See source code

Result returned by get_component_files().

Attributes:

dot_path instance-attribute ¤

dot_path: str

See source code

The python import path for the module. E.g. app.components.mycomp

filepath instance-attribute ¤

filepath: Path

See source code

The filesystem path to the module. E.g. /path/to/project/app/components/mycomp.py

ComponentRegistry ¤

ComponentRegistry(
    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None
)

Bases: object

See source code

Manages components and makes them available in the template, by default as {% component %} tags.

{% component "my_comp" key=value %}
{% endcomponent %}

To enable a component to be used in a template, the component must be registered with a component registry.

When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.

See Registering components.

Parameters:

  • library (Library, default: None ) –

    Django Library associated with this registry. If omitted, the default Library instance from django_components is used.

  • settings (Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]], default: None ) –

    Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.

Notes:

Example:

# Use with default Library
registry = ComponentRegistry()

# Or a custom one
my_lib = Library()
registry = ComponentRegistry(library=my_lib)

# Usage
registry.register("button", ButtonComponent)
registry.register("card", CardComponent)
registry.all()
registry.clear()
registry.get()

Using registry to share components¤

You can use component registry for isolating or "packaging" components:

  1. Create new instance of ComponentRegistry and Library:

    my_comps = Library()
    my_comps_reg = ComponentRegistry(library=my_comps)
    

  2. Register components to the registry:

    my_comps_reg.register("my_button", ButtonComponent)
    my_comps_reg.register("my_card", CardComponent)
    

  3. In your target project, load the Library associated with the registry:

    {% load my_comps %}
    

  4. Use the registered components in your templates:

    {% component "button" %}
    {% endcomponent %}
    

Methods:

Attributes:

library property ¤

library: Library

See source code

The template tag Library that is associated with the registry.

settings property ¤

settings: InternalRegistrySettings

See source code

Registry settings configured for this registry.

all ¤

all() -> Dict[str, Type[Component]]

See source code

Retrieve all registered Component classes.

Returns:

  • Dict[str, Type[Component]] –

    Dict[str, Type[Component]]: A dictionary of component names to component classes

Example:

# First register components
registry.register("button", ButtonComponent)
registry.register("card", CardComponent)
# Then get all
registry.all()
# > {
# >   "button": ButtonComponent,
# >   "card": CardComponent,
# > }

clear ¤

clear() -> None

See source code

Clears the registry, unregistering all components.

Example:

# First register components
registry.register("button", ButtonComponent)
registry.register("card", CardComponent)
# Then clear
registry.clear()
# Then get all
registry.all()
# > {}

get ¤

get(name: str) -> Type[Component]

See source code

Retrieve a Component class registered under the given name.

Parameters:

  • name (str) –

    The name under which the component was registered. Required.

Returns:

  • Type[Component] –

    Type[Component]: The component class registered under the given name.

Raises:

Example:

# First register component
registry.register("button", ButtonComponent)
# Then get
registry.get("button")
# > ButtonComponent

register ¤

register(name: str, component: Type[Component]) -> None

See source code

Register a Component class with this registry under the given name.

A component MUST be registered before it can be used in a template such as:

{% component "my_comp" %}
{% endcomponent %}

Parameters:

  • name (str) –

    The name under which the component will be registered. Required.

  • component (Type[Component]) –

    The component class to register. Required.

Raises:

  • AlreadyRegistered if a different component was already registered under the same name.

Example:

registry.register("button", ButtonComponent)

unregister ¤

unregister(name: str) -> None

See source code

Unregister the Component class that was registered under the given name.

Once a component is unregistered, it is no longer available in the templates.

Parameters:

  • name (str) –

    The name under which the component is registered. Required.

Raises:

Example:

# First register component
registry.register("button", ButtonComponent)
# Then unregister
registry.unregister("button")

ComponentVars ¤

Bases: tuple

See source code

Type for the variables available inside the component templates.

All variables here are scoped under component_vars., so e.g. attribute is_filled on this class is accessible inside the template as:

{{ component_vars.is_filled }}

Attributes:

is_filled instance-attribute ¤

is_filled: Dict[str, bool]

See source code

Dictonary describing which component slots are filled (True) or are not (False).

New in version 0.70

Use as {{ component_vars.is_filled }}

Example:

{# Render wrapping HTML only if the slot is defined #}
{% if component_vars.is_filled.my_slot %}
    <div class="slot-wrapper">
        {% slot "my_slot" / %}
    </div>
{% endif %}

This is equivalent to checking if a given key is among the slot fills:

class MyTable(Component):
    def get_context_data(self, *args, **kwargs):
        return {
            "my_slot_filled": "my_slot" in self.input.slots
        }

ComponentView ¤

ComponentView(component: Component, **kwargs: Any)

Bases: django.views.generic.base.View

See source code

Subclass of django.views.View where the Component instance is available via self.component.

Attributes:

component class-attribute instance-attribute ¤

component = component

ComponentsSettings ¤

Bases: tuple

See source code

Settings available for django_components.

Example:

COMPONENTS = ComponentsSettings(
    autodiscover=False,
    dirs = [BASE_DIR / "components"],
)

Attributes:

app_dirs class-attribute instance-attribute ¤

app_dirs: Optional[Sequence[str]] = None

See source code

Specify the app-level directories that contain your components.

Defaults to ["components"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(
    app_dirs=["my_comps"],
)

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(
    app_dirs=[],
)

autodiscover class-attribute instance-attribute ¤

autodiscover: Optional[bool] = None

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(
    autodiscover=False,
)

context_behavior class-attribute instance-attribute ¤

context_behavior: Optional[ContextBehaviorType] = None

See source code

Configure whether, inside a component template, you can use variables from the outside ("django") or not ("isolated"). This also affects what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Defaults to "django".

COMPONENTS = ComponentsSettings(
    context_behavior="isolated",
)

NOTE: context_behavior and slot_context_behavior options were merged in v0.70.

If you are migrating from BEFORE v0.67, set context_behavior to "django". From v0.67 to v0.78 (incl) the default value was "isolated".

For v0.79 and later, the default is again "django". See the rationale for change here.

dirs class-attribute instance-attribute ¤

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / "components"]. That is, the root components/ app.

Directories must be full paths, same as with STATICFILES_DIRS.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

COMPONENTS = ComponentsSettings(
    dirs=[BASE_DIR / "components"],
)

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(
    dirs=[],
)

dynamic_component_name class-attribute instance-attribute ¤

dynamic_component_name: Optional[str] = None

See source code

By default, the dynamic component is registered under the name "dynamic".

In case of a conflict, you can use this setting to change the component name used for the dynamic components.

# settings.py
COMPONENTS = ComponentsSettings(
    dynamic_component_name="my_dynamic",
)

After which you will be able to use the dynamic component with the new name:

{% component "my_dynamic" is=table_comp data=table_data headers=table_headers %}
    {% fill "pagination" %}
        {% component "pagination" / %}
    {% endfill %}
{% endcomponent %}

forbidden_static_files class-attribute instance-attribute ¤

forbidden_static_files: Optional[List[Union[str, Pattern]]] = None

libraries class-attribute instance-attribute ¤

libraries: Optional[List[str]] = None

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(
    libraries=[
        "mysite.components.forms",
        "mysite.components.buttons",
        "mysite.components.cards",
    ],
)

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):
    def ready(self):
        import "mysite.components.forms"
        import "mysite.components.buttons"
        import "mysite.components.cards"

Manually loading libraries¤

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries

import_libraries()

multiline_tags class-attribute instance-attribute ¤

multiline_tags: Optional[bool] = None

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(
    multiline_tags=False,
)

reload_on_file_change class-attribute instance-attribute ¤

reload_on_file_change: Optional[bool] = None

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

reload_on_template_change class-attribute instance-attribute ¤

reload_on_template_change: Optional[bool] = None

static_files_allowed class-attribute instance-attribute ¤

static_files_allowed: Optional[List[Union[str, Pattern]]] = None

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.

If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, JS, CSS, and common image and font file formats are considered static files:

COMPONENTS = ComponentsSettings(
    static_files_allowed=[
        ".css",
        ".js", ".jsx", ".ts", ".tsx",
        # Images
        ".apng", ".png", ".avif", ".gif", ".jpg",
        ".jpeg",  ".jfif", ".pjpeg", ".pjp", ".svg",
        ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
        # Fonts
        ".eot", ".ttf", ".woff", ".otf", ".svg",
    ],
)

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

static_files_forbidden class-attribute instance-attribute ¤

static_files_forbidden: Optional[List[Union[str, Pattern]]] = None

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(
    static_files_forbidden=[
        ".html", ".django", ".dj", ".tpl",
        # Python files
        ".py", ".pyc",
    ],
)

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

tag_formatter class-attribute instance-attribute ¤

tag_formatter: Optional[Union[TagFormatterABC, str]] = None

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to "django_components.component_formatter".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter

COMPONENTS = ComponentsSettings(
    "tag_formatter": component_formatter
)

Or as an import string;

COMPONENTS = ComponentsSettings(
    "tag_formatter": "django_components.component_formatter"
)

Examples:

  • "django_components.component_formatter"

    Set

    COMPONENTS = ComponentsSettings(
        "tag_formatter": "django_components.component_formatter"
    )
    

    To write components like this:

    {% component "button" href="..." %}
        Click me!
    {% endcomponent %}
    
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(
        "tag_formatter": "django_components.component_shorthand_formatter"
    )
    

    To write components like this:

    {% button href="..." %}
        Click me!
    {% endbutton %}
    

template_cache_size class-attribute instance-attribute ¤

template_cache_size: Optional[int] = None

See source code

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(
    template_cache_size=256,
)

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(
    template_cache_size=None,
)

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template

cached_template("Variable: {{ variable }}")

# You can optionally specify Template class, and other Template inputs:
class MyTemplate(Template):
    pass

cached_template(
    "Variable: {{ variable }}",
    template_cls=MyTemplate,
    name=...
    origin=...
    engine=...
)

ContextBehavior ¤

Bases: str, enum.Enum

See source code

Configure how (and whether) the context is passed to the component fills and what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Options:

  • django: With this setting, component fills behave as usual Django tags.
  • isolated: This setting makes the component fills behave similar to Vue or React.

Attributes:

DJANGO class-attribute instance-attribute ¤

DJANGO = 'django'

See source code

With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.

  1. Component fills use the context of the component they are within.
  2. Variables from Component.get_context_data() are available to the component fill.

Example:

Given this template

{% with cheese="feta" %}
  {% component 'my_comp' %}
    {{ my_var }}  # my_var
    {{ cheese }}  # cheese
  {% endcomponent %}
{% endwith %}

and this context returned from the Component.get_context_data() method

{ "my_var": 123 }

Then if component "my_comp" defines context

{ "my_var": 456 }

Then this will render:

456   # my_var
feta  # cheese

Because "my_comp" overrides the variable "my_var", so {{ my_var }} equals 456.

And variable "cheese" will equal feta, because the fill CAN access the current context.

ISOLATED class-attribute instance-attribute ¤

ISOLATED = 'isolated'

See source code

This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_context_data().

Example:

Given this template

{% with cheese="feta" %}
  {% component 'my_comp' %}
    {{ my_var }}  # my_var
    {{ cheese }}  # cheese
  {% endcomponent %}
{% endwith %}

and this context returned from the get_context_data() method

{ "my_var": 123 }

Then if component "my_comp" defines context

{ "my_var": 456 }

Then this will render:

123   # my_var
      # cheese

Because both variables "my_var" and "cheese" are taken from the root context. Since "cheese" is not defined in root context, it's empty.

EmptyDict ¤

Bases: dict

See source code

TypedDict with no members.

You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from Component.get_context_data() / Component.get_js_data() / Component.get_css_data():

Accepts NO kwargs:

from django_components import Component, EmptyDict

class Table(Component(Any, EmptyDict, Any, Any, Any, Any))
    ...

Accepts NO slots:

from django_components import Component, EmptyDict

class Table(Component(Any, Any, EmptyDict, Any, Any, Any))
    ...

Returns NO data from get_context_data():

from django_components import Component, EmptyDict

class Table(Component(Any, Any, Any, EmptyDict, Any, Any))
    ...

Going back to the example with NO kwargs, when you then call Component.render() or Component.render_to_response(), the kwargs parameter will raise type error if kwargs is anything else than an empty dict.

Table.render(
    kwargs: {},
)

Omitting kwargs is also fine:

Table.render()

Other values are not allowed. This will raise an error with MyPy:

Table.render(
    kwargs: {
        "one": 2,
        "three": 4,
    },
)

EmptyTuple module-attribute ¤

EmptyTuple = Tuple[]

See source code

Tuple with no members.

You can use this to define a Component that accepts NO positional arguments:

from django_components import Component, EmptyTuple

class Table(Component(EmptyTuple, Any, Any, Any, Any, Any))
    ...

After that, when you call Component.render() or Component.render_to_response(), the args parameter will raise type error if args is anything else than an empty tuple.

Table.render(
    args: (),
)

Omitting args is also fine:

Table.render()

Other values are not allowed. This will raise an error with MyPy:

Table.render(
    args: ("one", 2, "three"),
)

RegistrySettings ¤

Bases: tuple

See source code

Configuration for a ComponentRegistry.

These settings define how the components registered with this registry will behave when rendered.

from django_components import ComponentRegistry, RegistrySettings

registry_settings = RegistrySettings(
    context_behavior="django",
    tag_formatter="django_components.component_shorthand_formatter",
)

registry = ComponentRegistry(settings=registry_settings)

Attributes:

CONTEXT_BEHAVIOR class-attribute instance-attribute ¤

CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None

See source code

Deprecated. Use context_behavior instead. Will be removed in v1.

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

TAG_FORMATTER class-attribute instance-attribute ¤

TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None

See source code

Deprecated. Use tag_formatter instead. Will be removed in v1.

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

context_behavior class-attribute instance-attribute ¤

context_behavior: Optional[ContextBehaviorType] = None

See source code

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

tag_formatter class-attribute instance-attribute ¤

tag_formatter: Optional[Union[TagFormatterABC, str]] = None

See source code

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

Slot dataclass ¤

Slot(content_func: SlotFunc[TSlotData])

Bases: typing.Generic

See source code

This class holds the slot content function along with related metadata.

Attributes:

content_func instance-attribute ¤

content_func: SlotFunc[TSlotData]

do_not_call_in_templates property ¤

do_not_call_in_templates: bool

SlotContent module-attribute ¤

SlotContent = Union[SlotResult, SlotFunc[TSlotData], 'Slot[TSlotData]']

SlotFunc ¤

SlotRef ¤

SlotRef(slot: SlotNode, context: Context)

Bases: object

See source code

SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.

This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}, it will output the contents of the slot.

SlotResult module-attribute ¤

SlotResult = Union[str, SafeString]

TagFormatterABC ¤

Bases: abc.ABC

See source code

Abstract base class for defining custom tag formatters.

Tag formatters define how the component tags are used in the template.

Read more about Tag formatter.

For example, with the default tag formatter (ComponentFormatter), components are written as:

{% component "comp_name" %}
{% endcomponent %}

While with the shorthand tag formatter (ShorthandComponentFormatter), components are written as:

{% comp_name %}
{% endcomp_name %}

Example:

Implementation for ShorthandComponentFormatter:

from djagno_components import TagFormatterABC, TagResult

class ShorthandComponentFormatter(TagFormatterABC):
    def start_tag(self, name: str) -> str:
        return name

    def end_tag(self, name: str) -> str:
        return f"end{name}"

    def parse(self, tokens: List[str]) -> TagResult:
        tokens = [*tokens]
        name = tokens.pop(0)
        return TagResult(name, tokens)

Methods:

end_tag abstractmethod ¤

end_tag(name: str) -> str

See source code

Formats the end tag of a block component.

Parameters:

  • name (str) –

    Component's registered name. Required.

Returns:

  • str ( str ) –

    The formatted end tag.

parse abstractmethod ¤

parse(tokens: List[str]) -> TagResult

See source code

Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).

Parameters:

  • tokens ([List(str]) –

    List of tokens passed to the component tag.

Returns:

  • TagResult ( TagResult ) –

    Parsed component name and remaining tokens.

Example:

Assuming we used a component in a template like this:

{% component "my_comp" key=val key2=val2 %}
{% endcomponent %}

This function receives a list of tokens:

['component', '"my_comp"', 'key=val', 'key2=val2']
  • component is the tag name, which we drop.
  • "my_comp" is the component name, but we must remove the extra quotes.
  • The remaining tokens we pass unmodified, as that's the input to the component.

So in the end, we return:

TagResult('my_comp', ['key=val', 'key2=val2'])

start_tag abstractmethod ¤

start_tag(name: str) -> str

See source code

Formats the start tag of a component.

Parameters:

  • name (str) –

    Component's registered name. Required.

Returns:

  • str ( str ) –

    The formatted start tag.

TagResult ¤

Bases: tuple

See source code

The return value from TagFormatter.parse().

Read more about Tag formatter.

Attributes:

component_name instance-attribute ¤

component_name: str

See source code

Component name extracted from the template tag

For example, if we had tag

{% component "my_comp" key=val key2=val2 %}

Then component_name would be my_comp.

tokens instance-attribute ¤

tokens: List[str]

See source code

Remaining tokens (words) that were passed to the tag, with component name removed

For example, if we had tag

{% component "my_comp" key=val key2=val2 %}

Then tokens would be ['key=val', 'key2=val2'].

autodiscover ¤

autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]

See source code

Search for all python files in COMPONENTS.dirs and COMPONENTS.app_dirs and import them.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) –

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] –

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files

modules = get_component_files(".py")

cached_template ¤

cached_template(
    template_string: str,
    template_cls: Optional[Type[Template]] = None,
    origin: Optional[Origin] = None,
    name: Optional[str] = None,
    engine: Optional[Any] = None,
) -> Template

See source code

Create a Template instance that will be cached as per the COMPONENTS.template_cache_size setting.

Parameters:

  • template_string (str) –

    Template as a string, same as the first argument to Django's Template. Required.

  • template_cls (Type[Template], default: None ) –

    Specify the Template class that should be instantiated. Defaults to Django's Template class.

  • origin (Type[Origin], default: None ) –
  • name (Type[str], default: None ) –

    Sets Template.name

  • engine (Type[Any], default: None ) –

    Sets Template.engine

from django_components import cached_template

template = cached_template("Variable: {{ variable }}")

# You can optionally specify Template class, and other Template inputs:
class MyTemplate(Template):
    pass

template = cached_template(
    "Variable: {{ variable }}",
    template_cls=MyTemplate,
    name=...
    origin=...
    engine=...
)

get_component_dirs ¤

get_component_dirs(include_apps: bool = True) -> List[Path]

See source code

Get directories that may contain component files.

This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.

Parameters:

  • include_apps (bool, default: True ) –

    Include directories from installed Django apps. Defaults to True.

Returns:

  • List[Path] –

    List[Path]: A list of directories that may contain component files.

get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a "components" app.

In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).

Notes:

  • Paths that do not point to directories are ignored.

  • BASE_DIR setting is required.

  • The paths in COMPONENTS.dirs must be absolute paths.

get_component_files ¤

get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Parameters:

  • suffix (Optional[str], default: None ) –

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry] –

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files

modules = get_component_files(".py")

import_libraries ¤

import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) –

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] –

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries

class MyAppConfig(AppConfig):
    def ready(self):
        import_libraries()

Potential usage in tests

from django_components import import_libraries

import_libraries(lambda path: path.replace("tests.", "myapp."))

register ¤

register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[
    [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],
    Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],
]

See source code

Class decorator for registering a component to a component registry.

See Registering components.

Parameters:

  • name (str) –

    Registered name. This is the name by which the component will be accessed from within a template when using the {% component %} tag. Required.

  • registry (ComponentRegistry, default: None ) –

    Specify the registry to which to register this component. If omitted, component is registered to the default registry.

Raises:

  • AlreadyRegistered –

    If there is already a component registered under the same name.

Examples:

from django_components import Component, register

@register("my_component")
class MyComponent(Component):
    ...

Specifing ComponentRegistry the component should be registered to by setting the registry kwarg:

from django.template import Library
from django_components import Component, ComponentRegistry, register

my_lib = Library()
my_reg = ComponentRegistry(library=my_lib)

@register("my_component", registry=my_reg)
class MyComponent(Component):
    ...

registry module-attribute ¤

See source code

The default and global component registry. Use this instance to directly register or remove components:

See Registering components.

# Register components
registry.register("button", ButtonComponent)
registry.register("card", CardComponent)

# Get single
registry.get("button")

# Get all
registry.all()

# Unregister single
registry.unregister("button")

# Unregister all
registry.clear()

render_dependencies ¤

render_dependencies(content: TContent, type: RenderType = 'document') -> TContent

See source code

Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.

By default, the string is parsed as an HTML and: - CSS is inserted at the end of <head> (if present) - JS is inserted at the end of <body> (if present)

If you used {% component_js_dependencies %} or {% component_css_dependencies %}, then the JS and CSS will be inserted only at these locations.

Example:

def my_view(request):
    template = Template('''
        {% load components %}
        <!doctype html>
        <html>
            <head></head>
            <body>
                <h1>{{ table_name }}</h1>
                {% component "table" name=table_name / %}
            </body>
        </html>
    ''')

    html = template.render(
        Context({
            "table_name": request.GET["name"],
        })
    )

    # This inserts components' JS and CSS
    processed_html = render_dependencies(html)

    return HttpResponse(processed_html)