component_media - Django-Components" > component_media - Django-Components" >
Skip to content

component_media ¤

ComponentMediaInput ¤

Defines JS and CSS media files associated with this component.

MediaMeta ¤

Bases: MediaDefiningClass

Metaclass for handling media files for components.

Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

This subclass has following changes:

1. Support for multiple interfaces of JS/CSS¤
  1. As plain strings

    class MyComponent(Component):
        class Media:
            js = "path/to/script.js"
            css = "path/to/style.css"
    

  2. As lists

    class MyComponent(Component):
        class Media:
            js = ["path/to/script1.js", "path/to/script2.js"]
            css = ["path/to/style1.css", "path/to/style2.css"]
    

  3. [CSS ONLY] Dicts of strings

    class MyComponent(Component):
        class Media:
            css = {
                "all": "path/to/style1.css",
                "print": "path/to/style2.css",
            }
    

  4. [CSS ONLY] Dicts of lists

    class MyComponent(Component):
        class Media:
            css = {
                "all": ["path/to/style1.css"],
                "print": ["path/to/style2.css"],
            }
    

2. Media are first resolved relative to class definition file¤

E.g. if in a directory my_comp you have script.js and my_comp.py, and my_comp.py looks like this:

class MyComponent(Component):
    class Media:
        js = "script.js"

Then script.js will be resolved as my_comp/script.js.

3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof¤

E.g.:

def lazy_eval_css():
    # do something
    return path

class MyComponent(Component):
    class Media:
        js = b"script.js"
        css = lazy_eval_css
4. Subclass Media class with media_class¤

Normal MediaDefiningClass creates an instance of Media class under the media attribute. This class allows to override which class will be instantiated with media_class attribute:

class MyMedia(Media):
    def render_js(self):
        ...

class MyComponent(Component):
    media_class = MyMedia
    def get_context_data(self):
        assert isinstance(self.media, MyMedia)