0

I have a tuple, such that

{{VISIBILITY_CHOICES.1.1}}

Outputs "hello".

I have model "task" with a attribute "visibility_status", and in a loop, say all the iterations of task.visibility_status outputs 1

{{task.visibility_status}}

Outputs 1.

How do I use this task.visibility_status inside the lookup of the tuple? Something like VISIBILITY_CHOICES[task.visibility_status][1] in a different language.

I'm very new to django... Thanks a lot.

edit: The code I was running:

{% for task in tasks %}
    <div class="post">
         <h1><a href="">{{ task.subject }}</a></h1>
         <div class="date">
             <p>Due: {{ task.due_date }}</p>
             <p>Assigned to: {{task.assigned_to}}</p>
         </div>
         <p>{{ task.text_area|linebreaks }}</p>
         {% with args=""|add:task.visibility_status|add:",1" %}
         <p>Visibility Status: {{VISIBILITY_CHOICES|get_index:args}}({{ task.visibility_status }})</p>
         {% endwith %}
         <p>Case Status: {{ task.case_status }}</p>
         <div class="date">
             <p>Created: {{ task.created_date }} by {{ task.author }}</p>
         </div>
     </div>
{% endfor %}
Lim Jia Wei
  • 61
  • 2
  • 10
  • 1
    Write a custom template filter. See: [How can I use a variable as index in django template?](http://stackoverflow.com/questions/13376576/how-can-i-use-a-variable-as-index-in-django-template) – Moses Koledoye Jun 25 '16 at 20:00

1 Answers1

0

Although the builtin name tuple may not have any syntactic meaning in a template, I'll use my_tuple in its place in the code below.

I've used with to create a context that builds the args for indexing my_tuple (i.e task.visibility_status and 1): :

{% with x=task.visibility_status|stringformat:"s" %}
{% with args=x|add:",1" %}

    {{ my_tuple|get_index:args }}

{% endwith %}
{% endwith %}

And in the custom template filter, I've splitted and recreated the arguments and used indexing in plain python to return the item at the index:

from django import template

register = template.Library()

@register.filter
def get_index(my_tuple, args):
    arg1, arg2 = args.split(',') # split on the comma separator
    try:
        i = int(arg1)
        j = int(arg2)
        return my_tuple[i][j] # same as my_tuple[task.status][1]
    except: 
        return None
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139