我在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/09/02
这是我的观点:
## 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)
您试图在上下文中将year
作为整数传递。您需要在上下文中将year
的值作为字符串传递
你需要修改
year = 2015 # passing integer value is wrong here
year = '2015' # pass year in string
在您的例子中,add
内置模板过滤器需要两个值都是字符串或整数,以便正确执行加法。
此过滤器将首先尝试将两个值强制转换为整数。如果这如果失败,它将尝试将值加在一起。这是可行的对某些数据类型(字符串、列表等)执行,而对其他数据类型执行失败。如果它
在这里,你传递的一个值是字符串,另一个是整数,结果显示为空字符串
我认为在模板中做这种工作是个坏主意。但是如果出于某种原因必须创建自己的模板标签并使用os.path.join
。
os.path.join
将根据平台选择分隔符(适用于linux的/
和windows的)。
这样的模板标签可能看起来像:
@register.assignment_tag
def build_path(*args):
# or if you need only / as separator
# return "/".join([str(arg) for arg in args])
return os.path.join(*[str(arg) for arg in args])