python - 在Django中根据if条件选择for循环
问题描述
在 Django 中,如何编写条件以选择两个for
循环之一?
{% if type == 'type_one' %}
{% for object in type_one_ojects %}
{% elif type == 'type_two' %} # this_line
{% for object in type_two_ojects %}
...
########## Given error ##########
# Invalid block tag on this_line: 'elif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
解决方案
这样的逻辑不属于模板,而是属于视图。实际上,模板关注的是呈现逻辑,而不是业务逻辑。在视图中,您可以检查类型是否为type_one
ortype_two
并相应地传递项目集。
因此,视图应如下所示:
def some_view(request):
# …
objects = type_one_objects if type == 'type_one' else type_two_objects
context = { 'objects': objects }
return render(request, '%name_of_template.html', context)
然后在模板中枚举:
{% for object in objects %}
<!-- … -->
{% endfor %}
推荐阅读
- python - 删除从绘图中的自定义刻度创建的网格线
- email - 如何在 Go 中为电子邮件创建嵌套的多部分/MIME 信封?
- sql-server - 将多个表中的值按公共列分组
- ios - NativeScript ListView 滚动事件
- java - 哥德巴赫猜想(java)
- python - 准确地将字典返回到元组
- contacts - 提交托管在 DataFire 上的联系表单时出现“找不到路径:POST /”错误
- google-cloud-platform - Google Stackdriver Logging 向高级过滤器添加评论
- ios - 如何将 CALayer 的 contentGravity 变量设置为“resizeAspectFill”?
- git - git svn fetch 期间断电后出现致命错误