I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked.
Initially, everything was working smoothly with standard htmx functionality. However, I ran into problems when trying to add an active
css class to the category link after it has been clicked (to indicate the user's current location).
I experimented with hx-swap-oob
and hx-swap
, but the only solution that worked involved the following code snippet:
(this is the most relevant section of the code)
<div class="col-sm-4">
<div class="card">
<div class="card-body" hx-boost="true" hx-target="#manual_results">
<div id="manual_categories">
{% include 'partials/manual_categories.html' %}
</div>
</div>
</div>
</div>
<div class="col-sm-8">
<div id="manual_results">
{% include 'partials/manual_entries_list.html' %}
</div>
</div>
And in manual_entries_list.html
:
<some html results>
<div id="manual_categories" hx-swap-oob="true">
{% include 'partials/manual_categories.html' %}
</div>
Each category includes a simple if statement in the Django template code to determine if it is selected (based on the URL path).
Although this setup works, there is a slight hiccup where the categories are rendered twice on the first request (due to having 2 includes in the same HTML file). Once a category is selected, HTMX "catches on" and correctly switches the categories from manual_entries_list.html
to our main page.
To address this issue, I modified manual_entries_list.html
as follows:
<some html results>
<div class="set_size_to_0px">
<div id="manual_categories" hx-swap-oob="true">
{% include 'partials/manual_categories.html' %}
</div>
</div>
This ensures that the categories remain invisible (so only one set is visible at a time).
However, this feels like a temporary "hack." I'm certain there must be a more elegant solution to this problem, but I haven't been able to find it yet.
(I even attempted a plain JavaScript approach, but due to the categories being rendered in a loop, accurately obtaining IDs proved to be quite challenging.)
If anyone could provide assistance, I would greatly appreciate it.