Xzya / django-web-components

A simple way to create reusable template components in Django.
MIT License
159 stars 4 forks source link

Conditional slots (slot in if) #6

Open bygri opened 1 year ago

bygri commented 1 year ago

Hello, this package is great.

One issue encountered. It would be nice to be able to conditionally add slots:

{% card %}
  {% if perms.can_edit %}
    {% slot action %}<a href="/edit/">Edit</a>{% endslot %}
  {% endif %}
  …
{% endcard %}

However, the slot ends up being rendered regardless of the conditional block.

Xzya commented 1 year ago

Hello,

At the moment this is not supported, however, it sounds like an interesting feature so I will look into it.

In the meantime, there are several alternatives to this.

{% card %}
    {% slot action %}
        {% if perms.can_edit %}
            <a href="/edit/">Edit</a>
        {% endif %}
    {% endslot %}
{% endcard %}

However, this may not be what you want if you have logic around the slot existing inside the component, e.g. {% if slots.action %}{% render_slot slots.action %}{% endif %}.

{% card %}
    {% slot action show=perms.can_edit %}
        <a href="/edit/">Edit</a>
    {% endslot %}
{% endcard %}

...

<div>
    {% if slots.action.attributes.show %}
        {% render_slot slots.action %}
    {% endif %}
</div>
{% card %}
    ...

    {% if perms.can_edit %}
        {% card_action %}
            <a href="/edit/">Edit</a>
        {% endcard_action %}
    {% endif %}

    ...
{% endcard %}

These may or may not make sense depending on your use case.