Django:使用变量作为数组索引?
我正在尝试创建一个将项目放入表格中的模板。
控制器:
items = Item.all().order('name').fetch(10)
template_values = {'items': items,
'headers': ['Name', 'Price', 'Quantity']}
render('Views/table.html', self, template_values)
模板:
<table>
<tr>
{% for header in headers %}
<th>{{header}}</th>
{% endfor %}
</tr>
{% for item in items %}
<tr><td><a href="detail/{{item.CSIN}}">{{item.name}}</a></td><td>{{item.CSIN}}</td></tr>
{% endfor %}
</table>
现在,模板被硬编码以查找item
的某些属性。我想更改此设置,以便它查找具有 headers
中名称的属性,或者查找前 n 个属性,其中 n 是 headers
的长度代码>.
我该怎么做?
I am trying to create a template that will put items in a table.
Controller:
items = Item.all().order('name').fetch(10)
template_values = {'items': items,
'headers': ['Name', 'Price', 'Quantity']}
render('Views/table.html', self, template_values)
Template:
<table>
<tr>
{% for header in headers %}
<th>{{header}}</th>
{% endfor %}
</tr>
{% for item in items %}
<tr><td><a href="detail/{{item.CSIN}}">{{item.name}}</a></td><td>{{item.CSIN}}</td></tr>
{% endfor %}
</table>
Right now, the template is hard coded to look for certain attributes of item
. I want to change this so it either looks for the attributes with the names that are in headers
, or so that it looks for the first n attributes, where n is the length of headers
.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以调整视图来执行以下操作:
因此模板所要做的就是循环每个“项目”(这只是要显示与标题相对应的值的列表。基本上,这将移动逻辑(决定要显示什么内容) show)从模板(或者实际上在模板和视图中分别拆分一点)完全到视图中的Python代码,简化模板并使其更加通用,如您所愿。
You could tweak the view to do:
so all the template has to do is loop over each "item" (which will just be a list of the values to show corresponding to the headers. Basically, this would move the logic (deciding what to show) from the template (or actually split a bit each in template and view) entirely to the Python code in the view, simplifying the template and making it more general, as you desire.
我不确定是否有现有的模板标签/过滤器可以实现您想要的功能。您可以考虑编写一个自定义模板标签或过滤器,它接受项目列表和当前标题并在查找后返回值。看看 http://docs.djangoproject.com/en /dev/howto/custom-template-tags/。
I'm not sure if there is an existing template tag/filter that will accomplish what you want. You could look into writing a custom template tag or filter which accepts the items list and the current header and returns the value after the look-up. Have a look at http://docs.djangoproject.com/en/dev/howto/custom-template-tags/.