在Django模板中使用with和add来组合变量失败



我在Django模板中使用withadd组合变量时遇到了一些问题。

下面是我传递给模板的变量
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])

最新更新