hotwire-django / turbo-django

Unmaintained // An early stage integration of Hotwire Turbo with Django
https://discuss.hotwire.dev/t/django-backend-support-for-hotwire/1570/
Other
385 stars 20 forks source link

Turbo-Django 0.2.0 Update #37

Closed scuml closed 3 years ago

scuml commented 3 years ago

Major update to the turbo-django library. This includes breaking API changes but makes the library much more flexible to use.

Broadcasting now centers around Turbo objects. Create a Turbo object with the broadcast name, render a template, and then call one of the actions to send the html to the subscribed clients.

from turbo import Turbo

# Send a message with the current timestamp to the channel `broadcast_name` and
# update any element with the id 'broadcast_box`.
Turbo('broadcast_name').render_from_string(
    f"{datetime.now()}: This is a broadcast."
).update(id="broadcast_box")

# or for a model instance

room = Room.objects.first()

Turbo(room).render(
    "template.html", context={}
).append(id="broadcast_box")

# If using TurboMixin

room.turbo.render(
    "template.html", context={}
).append(selector="p.broadcast_class")

broadcast_to and broadcast_self were removed as they placed severe limitations on what could be broadcast. They have been replaced with ModelBroadcasts. ModelBroadcasts live in the file broadcasts.py and look like this:

@turbo.register(Message)
class MessageBroadcast(turbo.ModelBroadcast):

    def on_save(self, message, created, *args, **kwargs):
        if created:
            message.room.turbo.render("chat/message.html", {"message": message}).append(id="messages")
        else:
            message.room.turbo.render("chat/message.html", {"message": message}).replace(id=f"message-{message.id}")

    def on_delete(self, message, *args, **kwargs):
        message.room.turbo.remove(id=f"message-{message.id}")

This allows the user to explicitly send as many templates to as many channels as needed - and allows additional context to be sent to the template - all in a django-esque easy-to-read class.

Other changes include: