使用模板标记在html模板中求和

前端之家收集整理的这篇文章主要介绍了使用模板标记在html模板中求和前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 HTML中求和,但模板标签返回0,

View.py

  1. def gen_Report(request):
  2.  
  3. ### query returns below output
  4. list=[{'total': 1744,'user': u'x'},{'total': 13,'user': u'y'},{'total': 126,'user': u'z'},{'total': 46,'user': u'm'},{'total': 4,'user': u'n'},{'total': 8,'user': u'o'},{'total': 3,'user': u'p'}]
  5.  
  6. return render_to_response('user.html',locals(),context_instance = RequestContext(request))

模板:

  1. user.html
  2.  
  3. {% load temptags %}
  4.  
  5. <table id="myTable" class="tablesorter">
  6. <thead>
  7. <tr>
  8.  
  9. <th>S.No</th>
  10. <th>role</th>
  11. <th>Count</th>
  12.  
  13. </tr>
  14. </thead>
  15. {% for fetch in list %}
  16.  
  17. <tr>
  18. <td>{{forloop.counter}}</td>
  19. <td>{{fetch.user}}</td>
  20. <td>{{fetch.total}}</td>
  21.  
  22.  
  23.  
  24. {% endfor %}
  25. <td>{{ list.total|running_total}}</td>
  26. <tr>
  27.  
  28. </table>

模板标签

  1. from django.template import Library
  2. register = Library()
  3. @register.filter
  4. def running_total(list_total):
  5. return sum(d.get('list_sum') for d in list_total)

输出

  1. S.No user Count
  2. 1 x 1744
  3. 2 y 13
  4. 3 z 126
  5. 4 m 46
  6. 5 n 4
  7. 6 o 8
  8. Sum------------------> 0 (it returns zero)

我在这里做错了什么?

你可以帮助我,如何在这里使用模板标签返回总和?

解决方法

您的模板标记看起来不对.你有role_total作为参数,然后遍历list_total(看似未定义),并从列表中的每个字典尝试获取键list_sum,这似乎是未定义的.
  1. from django.template import Library
  2. register = Library()
  3. @register.filter
  4. def running_total(your_dict_list):
  5. return sum(d['total'] for d in your_dict_list)

并在< td> {{list | running_total}}< / td>的模板中调用

猜你在找的HTML相关文章