我得到一个arr
传递给我的Django模板的数组.我要访问的阵列中的阵列的各个元素(例如arr[0]
,arr[1]
)等等,而不是通过整个阵列循环.
有没有办法在Django模板中做到这一点?
Ned*_*der 296
请记住,Django模板中的点符号用于Python中的四种不同表示法.在模板中,foo.bar
可以表示以下任何一个:
foo[bar] # dictionary lookup
foo.bar # attribute lookup
foo.bar() # method call
foo[bar] # list-index lookup
Run Code Online (Sandbox Code Playgroud)
它按此顺序尝试它们,直到找到匹配项.因此foo.3
,您将获得列表索引,因为您的对象不是以3作为键的dict,没有名为3的属性,并且没有名为3的方法.
Ofr*_*viv 140
arr.0
arr.1
Run Code Online (Sandbox Code Playgroud)
等等
小智 12
When you render
a request to context
some information -
for example:
return render(request, 'path to template',{'username' :username , 'email'.email})
Run Code Online (Sandbox Code Playgroud)
you can access to it on template like this -
for variables
:
{% if username %}{{ username }}{% endif %}
Run Code Online (Sandbox Code Playgroud)
for arrays
:
{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}
Run Code Online (Sandbox Code Playgroud)
you can also name array objects in views.py
and then use it as shown below:
{% if username %}{{ username.first }}{% endif %}
Run Code Online (Sandbox Code Playgroud)
If you come across another problem, let me know, I am happy to help.