【问题标题】:Using with and add to combine variables failed in Django template在 Django 模板中使用 with 和 add 来组合变量失败
【发布时间】:2015-08-31 10:33:45
【问题描述】:

我在 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 年 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


【解决方案1】:

您试图在上下文中将year 作为整数传递。 您需要在上下文中将year 的值作为字符串传递。

你需要改变

year = 2015 # passing integer value is wrong here

year = '2015' # pass year in string

在您的情况下,add 内置模板过滤器需要两个值都是字符串或整数才能正确执行加法。

此过滤器将首先尝试将两个值强制转换为整数。如果这 失败,它会尝试将值相加。这将起作用 在某些数据类型(字符串、列表等)上失败,而在其他数据类型上失败。 如果是 失败,结果将是一个空字符串。

在这里,您将一个值作为字符串传递,另一个作为整数传递,这导致显示一个空字符串。

【讨论】:

  • 我尝试使用str(year)进行传输,但还是一样。
  • 你在哪里写str(year)
  • 在我看来,dict中有str(year)的for循环,然后将dict列表传递给template。
  • 请在您使用的模板中发布视图代码和循环代码,因为上面的代码对我来说是正确的。
  • 看起来值会被改变,但改变并没有应用到模板。它发生在我的其他变量和模板中。
【解决方案2】:

我认为在模板中做这种工作是个坏主意。但如果您出于某种原因必须创建自己的template tag 并使用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])

【讨论】:

    猜你喜欢
    • 2017-04-03
    • 2020-11-06
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2012-03-31
    相关资源
    最近更新 更多