11

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

But image_id is coming out as empty.

What am I doing wrong here?

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

Community
  • 1
  • 1
shrewdbeans
  • 11,971
  • 23
  • 69
  • 115
  • `add` filter tries to add as integers, if that fails it attempts to concatenate them. In your case, a number & string will cause an exception. You could define your own filter like this : http://stackoverflow.com/a/23783666/781695 – user May 21 '14 at 12:56

1 Answers1

23

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 %}
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Unfortunately that doesn't work. Perhaps because `the_id` is a number? – shrewdbeans Aug 29 '13 at 19:13
  • @shrewdbeans please check the updated answer (added `stringformat`). – alecxe Aug 29 '13 at 19:16
  • 3
    You can actually do it in just one step: `{% with image_id='image-'|add:vid.the_id|stringformat:"s" %}`. I've used `=` instead of `and` in the `with` since its the [recommended format](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#with) – gdvalderrama Oct 11 '17 at 11:17