from django.http import HttpRequest, HttpResponse
from django.utils.safestring import mark_safe
from django_components import Component, get_component_url, types
from .component import AlpineFragment, SimpleFragment
class FragmentsPage(Component):
class Media:
js = (
"https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,container-queries",
mark_safe(''),
)
def get_template_data(self, args, kwargs, slots, context):
# Get URLs that points to the FragmentsPageView.get() method
alpine_url = get_component_url(FragmentsPage, query={"type": "alpine"})
js_url = get_component_url(FragmentsPage, query={"type": "js"})
htmx_url = get_component_url(FragmentsPage, query={"type": "htmx"})
return {
"alpine_url": alpine_url,
"js_url": js_url,
"htmx_url": htmx_url,
}
template: types.django_html = """
{% load component_tags %}
HTML Fragments Example
HTML Fragments
This example shows how to load HTML fragments
using different client-side techniques.
Vanilla JS
Initial content
AlpineJS
HTMX
Initial content
"""
class View:
public = True
# The same GET endpoint handles rendering either the whole page or a fragment.
# We use the `type` query parameter to determine which one to render.
def get(self, request: HttpRequest) -> HttpResponse:
fragment_type = request.GET.get("type")
if fragment_type:
fragment_cls = AlpineFragment if fragment_type == "alpine" else SimpleFragment
return fragment_cls.render_to_response(
request=request,
deps_strategy="fragment",
kwargs={"type": fragment_type},
)
else:
return FragmentsPage.render_to_response(
request=request,
deps_strategy="fragment",
)