views:

36

answers:

1

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.

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

then you can:

{{ year_est|labeled:"Year Established: " }}
Ned Batchelder
This works in almost all cases, but for integers I had to use stringfilter otherwise it threw a type error. However for integers now if it is empty it says None. For instance Year Established is stored as an integer so if it's empty it reads.Year Established: None
Tristan O'Neil