super9
super9

Reputation: 30131

Django template tag that takes in a boolean and returns html

I have this bit of HTML that is going to be used in multiple places.

            {% if event.finished_payments %}
            <span class="label label-success">Complete</span>
            {% else %}
            <span class="label label-important">Incomplete</span>
            {% endif %}

I want to write a template tag that takes in a bool and returns <span class="label label-success">Complete</span> or <span class="label label-important">Incomplete</span> depending on whether the argument is True or False which I suppose looks something like this:

{% tf_label event.finished_payments %}

Alternatively, is another way of achieving this using the include template tag and pass in parameters?

Upvotes: 1

Views: 848

Answers (2)

DrTyrsa
DrTyrsa

Reputation: 31991

{{ event.finished_payments|yesno:"<span class='label label-success'>Complete</span>,<span class='label label-important'>Incomplete</span>" }}

But it think, using {% if %} tag is the best idea here, it's more readable. Anyway HTML should live in templates, not in Python code.

Upvotes: 5

Wesley
Wesley

Reputation: 2264

This should do the trick (not tested):

from django import template

register = template.Library()

@register.simple_tag
def tf_label(request, complete):
    if complete:
        element = '<span class="label label-success">Complete</span>'
    else
        element = '<span class="label label-important">Incomplete</span>'

    return element

Upvotes: 4

Related Questions