from django_components import Component, types # HTML into which a fragment will be loaded using vanilla JS class FragmentBaseJs(Component): class View: def get(self, request): return FragmentBaseJs.render_to_response(request=request) template: types.django_html = """ {% load component_tags %} {% component_css_dependencies %}
OLD
{% component_js_dependencies %} """ # HTML into which a fragment will be loaded using AlpineJs class FragmentBaseAlpine(Component): class View: def get(self, request): return FragmentBaseAlpine.render_to_response(request=request) template: types.django_html = """ {% load component_tags %} {% component_css_dependencies %}
OLD
{% component_js_dependencies %} """ # HTML into which a fragment will be loaded using HTMX class FragmentBaseHtmx(Component): class View: def get(self, request): return FragmentBaseHtmx.render_to_response(request=request) template: types.django_html = """ {% load component_tags %} {% component_css_dependencies %}
OLD
{% component_js_dependencies %} """ # Fragment where the JS and CSS are defined on the Component class FragJs(Component): class View: def get(self, request): return FragJs.render_to_response(request=request, deps_strategy="fragment") template: types.django_html = """
123
""" js: types.js = """ document.querySelector('#frag-text').textContent = 'xxx'; """ css: types.css = """ .frag { background: blue; } """ # Fragment that defines an AlpineJS component class FragAlpine(Component): class View: def get(self, request): return FragAlpine.render_to_response(request=request, deps_strategy="fragment") # NOTE: We wrap the actual fragment in a template tag with x-if="false" to prevent it # from being rendered until we have registered the component with AlpineJS. template: types.django_html = """ """ js: types.js = """ Alpine.data('frag', () => ({ fragVal: 'xxx', })); // Now that the component has been defined in AlpineJS, we can "activate" all instances // where we use the `x-data="frag"` directive. document.querySelectorAll('[data-name="frag"]').forEach((el) => { el.setAttribute('x-if', 'true'); }); """ css: types.css = """ .frag { background: blue; } """