Thwe
Thwe

Reputation: 175

How to display array value in Django template?

I have the following array and would like to display day name in the template.

DAYS = ((0, "Saturday"),
        (1, "Sunday"),
        (2, "Monday"),
        (3, "Tuesday"),
        (4, "Wednesday"))

I can display Monday by using {{ DAYS.2.1 }} but I was unable to display using {{DAYS.class_weekday.key_value.1}}.

I am getting class_weekday.key_value from a for loop but when I use class_weekday.key_value there then it's not showing anything!

Thank you!

Upvotes: 0

Views: 5745

Answers (3)

Ritesh Bisht
Ritesh Bisht

Reputation: 182

As per django

https://docs.djangoproject.com/en/1.10/ref/templates/api/#variables-and-lookups

Variables and lookups

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

Dictionary lookup. Example: foo["bar"]
Attribute lookup. Example: foo.bar
List-index lookup. Example: foo[bar]

Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context.

So you can use custom filter for this purpose.

You can make custom template filter:

#here, import DAYS
@register.filter
def return_day(i):
    try:
        return DAYS[i][1]
    except:
        return N.A

And in template

{{ class_weekday.key_value|return_day }}

Upvotes: 1

MaximeK
MaximeK

Reputation: 2061

What you want is DAYS[2][1] :)

Upvotes: -2

Francois
Francois

Reputation: 524

You can use

{{ instance.get_day_display }}

in your templates. That select the display value instead of the database value.

If you want to display all the values :

[ x for x, y in DAYS ]

will return a list containing the list of days,

Upvotes: 5

Related Questions