[Fixed]-How to access an array index by its value in a Django Template?

1👍

I don’t think it’s possible usind built-in Django Template features, because Django discourages adding too much logic to the templates. You could create another function that returns the current step index instead of it’s value.

If you really need to do this on the template (even though it’s not recommended), you could write a Custom template filter like the one below:

from django import template

register = template.Library()

@register.filter(name='cut')
def list_index_from_value(list_, value):
    return list_.index(value)

And on the template you could use like that:

{{ steps|list_index_from_value:step }}

0👍

It’s unclear what is process variable, but it seems to me that this is kind of object of some class.

You can rewrite process.get_current_step() to return step name and it’s index

class Process:
    _current_step = 0
    steps = ['passo_open','passo_edit','passo_add_file','passo_judge']

    def get_current_step():
        return steps[_current_step], _current_step

here .get_current_step() will return tuple, where first value would be step name and second one would be current_step

If you want your variable to store only your step name then use

step, _ = process.get_current_step()

If you want to have tuple then just

step = process.get_current_step()

And then in your template you would have

{{ step }}  # prints 'passo_judge', 1

Leave a comment