【问题标题】:Django template error: could not parse the remainderDjango 模板错误:无法解析剩余部分
【发布时间】:2016-04-03 09:00:06
【问题描述】:

我正在尝试从 Django(1.6.11) 模板中的 dict 呈现一个值。 unit_list 是单元(模型)的列表。 unit.unit_id 是单元的主键。 tags_dict 是标签的字典,其中 unit_ids 作为键,标签作为值。

{% for unit in unit_list %}
<tr>
    <td>{{ unit.unit_id }}</td>
    <td>{{ unit.version }}</td>
    <td>{{ unit.release_dt|date:'Y-m-d' }} {{ unit.release_dt|time:'H:i:s' }}</td>
    <td>{{ unit.update_dt|date:'Y-m-d' }} {{ unit.update_dt|time:'H:i:s' }}</td>
    <td>
        {{ tags_dict[unicode(unit)] }}
    </td>
    <td>{{ unit.last_modified|date:'Y-m-d' }} {{ unit.last_modified|time:'H:i:s' }}</td>
</tr>
{% endfor %}

但是我收到了这个错误:

Could not parse the remainder: '(unicode(unit))' from 'tags_dict.get(unicode(unit))'

【问题讨论】:

  • 如果您删除对unitunicode 调用,此错误会消失吗?
  • 然后错误是使用“(单位)”。我想我只需要在模板中删除带有 () 的方法调用
  • 是的,unicode 是一个内置函数,但它在 {{}} 中不起作用——这就是它失败的原因。

标签: python django django-templates jinja2


【解决方案1】:

这是因为您不能将这样的函数调用放入 Django 模板中。看起来您应该在视图中执行此操作并将其作为变量传递给模板。您还可以在单​​元类上添加一个方法,如下所示:

def get_tags(self):
    tags_dict = {} # TODO: retrieve tags dict.
    return tags_dict[unicode(self)]

然后,您可以在模板中执行以下操作:{{ unit.get_tags }}

【讨论】:

  • 这可能不是最合适的解决方案,因为字典必须在每次迭代中构建。模板标签将是更合适的解决方案
  • @karthikr 我的意思是字典可以从某个地方检索,而不是每次都创建。见编辑。
  • 当然可以,但是检索会如何发生呢?由于它是一个标签字典,因此必须动态检索它。既然你已经有了 this is context,为什么不利用它呢?我并不是说这行不通。我要说的是,拥有simple_tag 效率更高。你的想法?
  • @karthikr 你是对的。但是,很难说 OP 是如何获取标签字典的,所以我们不知道它的创建有多复杂。
【解决方案2】:

只需像这样删除空格:

<td>{{unit.last_modified|date:'Y-m-d'}}{{unit.last_modified|time:'H:i:s'}}</td>

【讨论】:

  • 是的!无需按照标记答案的建议进行操作。如果你有空格,这就是问题。
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 2017-11-18
  • 1970-01-01
  • 2015-05-05
  • 2011-07-11
  • 2015-03-06
  • 2016-06-13
  • 2011-04-03
相关资源
最近更新 更多