【发布时间】:2015-08-31 10:33:45
【问题描述】:
我在 Django 模板中使用with 和add 组合变量时遇到了一些问题。
这是我传递给模板的变量
year = 2015
source = u'temp_dir'
在我的模板中,with 在下方,但temp 仍为空。
{% with temp="home/"|add:source|add:"/"|add:year %}
{{temp}}
{% withend %}
当我从temp 中删除year 时,temp 的值变为home/temp_dir/(这是正确的)
{% with temp="home/"|add:source|add:"/"%}
{{temp}}
{% withend %}
我也尝试过将year 转移到 unicode
year = u'2015'
source = u'temp_dir'
但它仍然是空的,year 似乎有问题。
2015 年 9 月 2 日更新
这是我的看法:
## I will get a list of dicts from the db then do..
for result in results:
result.year = unicode(result.year)
return results
回答
当从 db 查询时,它返回一个 QuerySet 对象,并且它不允许我的程序将新键插入到 QuerySet 对象中的每个字典中。但是当我将它们复制到另一个字典列表中时,我可以在其中添加新密钥。
旧代码:
## I will get a list of dicts from the db then do..
for result in results:
result.year = unicode(result.year)
passed_dict['results'] = results
return render_to_response(index.html, passed_dict)
新代码:
final_results = []
for result in results:
temp_result = result
temp_result.year = unicode(result.year)
final_results.append(temp_result)
passed_dict['results'] = final_results
return render_to_response(index.html, passed_dict)
【问题讨论】:
-
使用 context['year'] = u'2015' 对我有用(Django 1.8.3)。文档说如果方法失败,结果将是一个空字符串。
-
我不明白。
unicode(year)和context['year'] = u'2015'有什么区别
标签: python django django-templates