Tristan O'Neil
Tristan O'Neil

Reputation: 331

Django Template Headings

Is there a way in Django templates to show a heading for a field (name of the field) only if the field has a value.

For instance if one of the fields was called Year Established it might look something like this.

Year Established: 1985

But if the field was empty then it wouldn't show Year Established like this.

Year Estabished:

I know you could do an if statement around each field but with over 50 fields this seems a little tedious, messy and redundant.

Upvotes: 0

Views: 86

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375584

@register.filter
def labeled(value, label):
    if value:
        return label + value
    else:
        return ""

then you can:

{{ year_est|labeled:"Year Established: " }}

Upvotes: 3

Related Questions