【问题标题】:How to concatenate a string to a number inside a template tag in Django如何将字符串连接到Django模板标签内的数字
【发布时间】:2013-09-02 08:51:04
【问题描述】:

我找到了similar question on StackOverflow,但该解决方案似乎对我不起作用,除非我做错了。我有一个 ID 号,我想将它附加到模板标签中的字符串中。这是我的尝试:

{% with "image-"|add:vid.the_id as image_id %}
     {# custom template tag to generate image #}
    {% image vid.teaser_thumbnail alt=vid.title id=image_id %}
{% endwith %}

image_id 显示为空。

我在这里做错了什么?

我想要的image_id 输出类似于“image-8989723123”。

【问题讨论】:

  • add 过滤器尝试添加为整数,如果失败,它会尝试连接它们。在您的情况下,数字和字符串将导致异常。您可以像这样定义自己的过滤器:stackoverflow.com/a/23783666/781695

标签: django django-templates


【解决方案1】:

试试这个方法(在你的上面添加with 声明和stringformat):

{% with vid.the_id|stringformat:"s" as vid_id %}
    {% with "image-"|add:vid_id as image_id %}
         {# custom template tag to generate image #}
         {% image vid.teaser_thumbnail alt=vid.title id=image_id %}
    {% endwith %}
{% endwith %}

【讨论】:

  • 不幸的是,这不起作用。也许是因为the_id 是一个数字?
  • @shrewdbeans 请检查更新后的答案(添加stringformat)。
  • 您实际上只需一步即可完成:{% with image_id='image-'|add:vid.the_id|stringformat:"s" %}。我在with 中使用了= 而不是and,因为它是recommended format
猜你喜欢
  • 2015-02-26
  • 2011-08-09
  • 1970-01-01
  • 2011-05-22
  • 2012-11-17
  • 2017-03-19
  • 2023-03-24
相关资源
最近更新 更多