2017-05-06 148 views
0

我有一个步骤数组和一个方法来访问在哪一步的过程。此方法返回进程名称。我需要得到数组的位置,其值等于我所在的步骤。如何通过在Django模板中的值访问数组索引?

例子:

模型

# models.py 

steps = ['passo_open','passo_edit','passo_add_file','passo_judge'] 

step = process.get_current_step() 

print step 
#prints 'passo_edit' 

模板

# mytemplate.html 

{{ step }} 
# prints 'passo_edit' 

{{ steps }} 
# prints ['passo_open','passo_edit','passo_add_file','passo_judge'] 

我需要的是拿到1改为:

myStep = 1 

我知道我可以得到一步索引,例如:

{{ steps.3 }} ## prints 'passo_judge' 

我需要的是:

# value = how_to_get_index(steps,step) 
    # print value 
    # prints 3 

我有一堆的步骤,链接,但我必须要打印仅当它比NEXT_STEP低。这就是为什么我必须得到该号码,以便我可以打印模板中的链接,直到myStep。如何通过Django模板中的值获取数组的索引?

+0

目前还不清楚你是真的想要什么,你有一个数组,你什么真正想要的? 'next_step'从哪里来? –

+0

myStep是我想要的。我有一个返回步骤名称的函数,以及其他返回所有步骤的函数。我想获得元素值等于我拥有的值的数组的索引,在这种情况下是步骤。我编辑了这个问题。 –

回答

1

我不认为这是可能的使用内置的Django模板功能,因为Django不鼓励向模板添加太多的逻辑。您可以创建另一个返回当前步骤索引而不是其值的函数。

如果你真的需要做到这一点的模板(即使它不推荐),你可以写一个Custom template filter像下面这样:

from django import template 

register = template.Library() 

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

,并且模板,你可以使用这样的:

{{ steps|list_index_from_value:step }} 
0

目前还不清楚什么是process变量,但在我看来,这是某种类的对象。

可以重写process.get_current_step()返回步骤名称和它的指数

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 

这里.get_current_step()将返回tuple,其中第一个值是,如果你希望你的变量步骤名称和第二个是CURRENT_STEP

只存储你的步骤名称然后使用

step, _ = process.get_current_step() 

如果你想有元组ñ只是

step = process.get_current_step() 

,然后在模板中,您将有

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

是的,过程是一个对象。我不能重写函数,因为它在代码中的其他地方使用。我已经考虑过了,在models.py中创建另一个方法来获取数组的索引。我会看看能做些什么。谢谢! –

+1

我相信应该有一种返回当前步骤的方法。 –