如何在Django的模板标签内将字符串连接到数字 [英] How to concatenate a string to a number inside a template tag in Django

查看:353
本文介绍了如何在Django的模板标签内将字符串连接到数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StackOverflow上找到了类似问题,但是除非我做错了,否则该解决方案似乎对我不起作用。我有一个ID号,我想将其附加到模板标签的字符串中。这是我的尝试:

I've found a similar question on StackOverflow, but the solution doesn't seem to work for me, unless I'm doing it wrong. I have a ID number, which I'd like to append to a string in a template tag. Here's my attempt:

{% 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。

My desired output of image_id would be something like "image-8989723123".

推荐答案

尝试这种方式(在 with 语句中添加<在您的顶部加上href = https://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat rel = noreferrer> stringformat ):

Try this way (added with statement with stringformat on top of yours):

{% 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 %}

这篇关于如何在Django的模板标签内将字符串连接到数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆