【问题标题】:Sum in html template using template tag使用模板标签在html模板中求和
【发布时间】:2011-07-13 15:16:07
【问题描述】:

我正在尝试在 HTML 中求和,但模板标签返回 0,

查看.py

def gen_Report(request):

### query returns below output 
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'}]

return render_to_response('user.html', locals(),
                            context_instance = RequestContext(request))

模板:

user.html

  {% load temptags %}

 <table id="myTable" class="tablesorter">
    <thead>
    <tr>

    <th>S.No</th>
    <th>role</th>
    <th>Count</th>

    </tr>
    </thead>
    {% for fetch in list %}

    <tr>
    <td>{{forloop.counter}}</td>
    <td>{{fetch.user}}</td>
    <td>{{fetch.total}}</td>



    {% endfor %}
    <td>{{ list.total|running_total}}</td>
    <tr>

    </table>

模板标签:

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

输出:

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

我在这里做错了什么?

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

【问题讨论】:

    标签: python django django-templates django-template-filters


    【解决方案1】:

    您的模板标签看起来不对。您将role_total 作为参数,然后遍历list_total(似乎未定义)并从列表中的每个字典尝试获取似乎也未定义的键list_sum

    from django.template import Library
    register = Library()
    @register.filter
    def running_total(your_dict_list):
       return sum(d['total'] for d in your_dict_list)
    

    并从模板中调用它&lt;td&gt;{{ list|running_total}}&lt;/td&gt;

    【讨论】:

      【解决方案2】:

      我怀疑您的列表是一个迭代器。所以第一次迭代,第二次迭代什么都没有。 所以你应该做这样的事情

      for d in list_total:
         d.set('list_sum', list(d.get('list_sum')))
      

      调用模板之前

      【讨论】:

      • 我需要添加视图或模板标签吗?
      猜你喜欢
      • 2014-03-20
      • 1970-01-01
      • 2022-11-25
      • 2011-06-15
      • 1970-01-01
      • 2011-09-24
      • 2014-12-10
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多