wrabit / django-cotton

Enabling Modern UI Composition in Django
https://django-cotton.com
MIT License
506 stars 20 forks source link

Ability to render a cotton component from a view? #152

Closed hanerlend closed 1 month ago

hanerlend commented 1 month ago

Hi,

I'm trying out cotton, alongside a couple of other component solutions for Django, like slippers and django-template-partials, together with HTMX.

So far I really like the speed and ease of use that Cotton provides.

Using a simple task-app as an example, this is what I would write in views.py if I were to use django-template-partials :

@require_http_methods(["GET", "PATCH", "DELETE"])
@login_required
def task(request, id):
    task = Task.objects.get(id=id)

    if request.method == "GET":
        context = {"task": task}
        return render(request, "myapp/tasks.html#line", context)

    elif request.method == "PATCH":
        data = QueryDict(request.body).dict()
        if "complete" in data.keys():
            data["complete"] = string_to_bool(data["complete"])

        for name, value in data.items():
            setattr(task, name, value)
        task.save()

        context = {"task": task}
        return render(request, "myapp/tasks.html#line", context)

    elif request.method == "DELETE":
        task.delete()
        return HttpResponse()

When using HTMX and cotton, however, I'm a bit unsure - what would be the preferred way to access components when doing a partial reload?

Would you simply address the components directly with "return render(request, "cotton/table_row.html", context)"?

copyfactory commented 1 month ago

I just render the components inside partials and never return 'just a cotton component'.

For a to-do app, you would likely have a cotton component for the todo card. After that, just render the to-dos using template partials as normal.

Let me know if that makes sense :)

wrabit commented 1 month ago

@hanerlend There's nothing specific, I would just mentally place it that a partial can contain any HTML, DTL with or without inserted cotton components.

hanerlend commented 1 month ago

@hanerlend There's nothing specific, I would just mentally place it that a partial can contain any HTML, DTL with or without inserted cotton components.

That makes sense.

Thinking of it, the component itself does not include anything specific, so I could have a component

"templates/cotton/table-row" containing

{% for row in rows %}
<tr>
    {% for cell in row %}
    <td>
        {{ cell }}
    </td>
    {% endfor %}
</tr>
{% endfor %}

and I could reference it directly

return render(request, "cotton/table_row.html", context)

Thanks for making it clear! 😊👍

hanerlend commented 1 month ago

I just render the components inside partials and never return 'just a cotton component'.

@copyfactory thanks! That may be the best way to do it, to make the code consistent, especially within teams.