Django: custom HTML tag

459 Views Asked by At

I want to clean up templates where something like this is very frequent:

<div class="some-class
  {% if x %}
    {% if x.a %} class_x_a {% else %} class_x_b {% endif %}
  {% elif y %}
    class_y
  {% else %}
    class_z
  {% endif %}"

  data-a="{{ a }}"
  data-b="{{ b }}"
  data-c="{{ c }}"
>
...
</div>

I wonder if there is any way to create a custom tag to clear this up, something like this:

{% custom_tag x y z a b c %}

And that would render the HTML from above.

I have tried using simple_tag but I cannot work around the closing tag. I mean, I could just do this:

{% custom_tag x y z a b c %}
  ...
</div>

But this doesn't seem like a good solution.

Or even:

{% custom_tag x y z a b c %}
  ...
{% close_tag 'div' %}

Also, using simpletag is a bit dirty as well because string format needs to be used. I wonder if there is a HTML element builder class or factory, so your tag could be built this way:

custom_tag = HTMLTag('div')
if x:
  custom_tag.add_class('x.a' if x.a else 'x.b')
elif y:
  custom_tag.add_class('y')
else:
  custom_tag.add_class('z')
custom_tag.data('a', a)
custom_tag.data('b', b)
custom_tag.data('c', c)

Can all this be done in an elegant way?

0

There are 0 best solutions below