# HTMX Tabs Demo ## Example Overview This example demonstrates how to use Bootstrap 5 tabs with **[HTMX](https://htmx.org/)** to load tab content (including `django_tomselect` fields) dynamically without full page reloads. Each tab fires its own HTMX request when selected, and the initially active tab loads on page load. Use this when you want to defer rendering a form until its tab is actually opened. --- ## Key Code Segments ### Main Template with Tabs Structure The main template sets up the Bootstrap 5 tabs and configures HTMX requests for each tab. :::{admonition} HTMX Tabs Template :class: dropdown ```html
``` ::: - **Purpose**: Creates a tabbed interface where each tab triggers an HTMX request to load content dynamically. - **Key HTMX Attributes**: - `data-hx-get`: The URL to fetch content from when the tab is clicked - `data-hx-trigger`: When to trigger the request (on click or load) - `data-hx-target`: Where to place the loaded content --- ### Tab Content Fragment Template The fragment template defines the content that will be loaded into each tab. :::{admonition} Tab Content Fragment Template :class: dropdown ```html {% load static %} {{ form.media }}

Loading content via htmx Demo

This page demonstrates loading the form using htmx.
{% csrf_token %} {{ form.as_div }}
``` ::: --- ### View Functions The view functions handle both the main page and the tab content fragments. :::{admonition} HTMX Tabs Views :class: dropdown ```python def htmx_tabs_view(request: HttpRequest) -> HttpResponse: """View for the htmx tabs demo page.""" template = "example/basic_demos/htmx_tabs.html" context = {} return TemplateResponse(request, template, context) def htmx_form_fragment_view(request: HttpRequest) -> HttpResponse: """View for the htmx form fragment page.""" template = "example/basic_demos/htmx_fragment.html" context = {} form = Bootstrap5StylingHTMXForm(request.POST or None) if request.POST: if form.is_valid(): messages.success(request, "Form submitted successfully!") else: messages.error(request, "Please correct the errors in the form before proceeding.") return HttpResponseRedirect("/") # Get the tab parameter to customize content if needed tab = request.GET.get('tab', '1') context["form"] = form context["tab_id"] = tab context["tab_title"] = f"Tab {tab} Content" return TemplateResponse(request, template, context) ``` ::: --- ## Implementation Notes - Each tab link contains the necessary HTMX attributes to trigger content loading - The initially active tab loads its content via the `data-hx-trigger="load"` attribute - Bootstrap's tab styling and behavior are preserved while enhancing with dynamic content loading ## Related - {doc}`htmx` - the base HTMX demo, covering the `use_htmx=True` config flag for HTMX-swapped content.