Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moving from jQuery to HTMX #42

Open
htukiain opened this issue Jan 29, 2022 · 0 comments
Open

Moving from jQuery to HTMX #42

htukiain opened this issue Jan 29, 2022 · 0 comments

Comments

@htukiain
Copy link

htukiain commented Jan 29, 2022

I started to use HTMX in my Django site.
HTMX is guite often used with lazy loading with paginated querysets.
This leads to fact that the first page has the Jquery, and as the lazy loaded objects are insterted into DOM the event listeners are not added. (Or atleast I could get them working)

The solution for me was to make django-likes to work with HTMX. Changes are quite small and remove totally depency to JQuery - which I suppose is good. :-)

I tried to keep the changes at minimum and I am sure that with further work the implementation could be nicer.

as example the button.html is changed to:

<div 
hx-post="{% url 'add_or_remove_hx' target_object_id target_model %}"
hx-target="this"
hx-swap="outerHTML"

data-toggle="tooltip" title="{{like_names}}" class="like float-end m-2 lead" model="{{ target_model }}" id="target_{{ target_object_id }}" style="color: red;">
    	<i class="like-{{ target_object_id }}  {% if not undo %} far {% else %} fas {% endif %}fa-heart"></i>
  		<span class="like-count-{{ target_object_id }}"> {{ like_count }}</span>
</div>

and add_or_remove in views is changed to

@login_required
def add_or_remove_hx(request, target_object_id, target_model):

    user = request.user

    try:
        app_model = target_model
        obj_id = target_object_id
    except (KeyError, ValueError):
        return HttpResponseBadRequest()

    like = Like.objects.get_like(user, obj_id, model=app_model)

    undo = False
    if like is None:
        Like.objects.create(user, obj_id, app_model)
        status = 'added'
        undo = True
    else:
        like.delete()
        status = 'deleted'
        undo = False

    likeCount=Like.objects.for_object(obj_id, app_model).count()


    context ={
        "target_model" : app_model,
        "target_object_id": obj_id,
        "like_count": likeCount,
        "undo": undo
    }


    return render(request, "likes/button.html", context)

And likes.js is removed.
And htmx needs to be included in the base.html (or on page-by-page basis)

<script src="https://unpkg.com/[email protected]"></script>

rest is untouched! :-)

Quite small changes and JQuery is gone!

Should I make a PR on this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant