首页 > 解决方案 > 为什么在这里提出 django TemplateSyntaxError ?

问题描述

我试图遍历我的视图的上下文并仅获取 'ga:deviceCategory' 值,我在 HTML 中运行的代码是:

<div class="card-body">
  {% for i in pvdc %}
    <p>{{ i.get('ga:deviceCategory') }}</p>
  {% endfor %}
</div>

我对 django 的看法是:

def dashboard(request):
  context = {'pvdc': [{'ga:deviceCategory': 'desktop', 'ga:pageviews': 673, 'ga:avgSessionDuration': 53.4447946},
{'ga:deviceCategory': 'mobile', 'ga:pageviews': 2373, 'ga:avgSessionDuration': 69.62674418604651},
{'ga:deviceCategory': 'tablet', 'ga:pageviews': 322, 'ga:avgSessionDuration': 26.205426356589147}]}
  return render(request, 'user/index.html', context)

我收到的语法错误是:无法解析剩余部分:来自 'i.get('ga:deviceCategory')' 的 '('ga:deviceCategory')'

在此处输入图像描述

这里有什么问题,我怎样才能得到这些值?

标签: pythondjangodjango-templates

解决方案


数据不是从 for 循环中呈现的,因此您需要从中删除 get

{{ i.get('ga:deviceCategory') }}

<div class="card-body">
  {% for i in pvdc %}
    <p>{{ i.'ga:deviceCategory'}}</p>
  {% endfor %}
</div>

推荐阅读