简体   繁体   中英

Django passing variables into string

I'm trying to pass:

>img src="{% static '/static_dirs/images/itcg/01_{{ card_id }}.jpg' %}" alt="{{ card_id }}">

to load image with file name 01_xx.jpg, but the result is just xx without image. Basically what happens is that {{ card_id }} works in alt but I can't load the image. I have tried to change 01_{{ card_id }}.jpg into 01_01.jpg and it works, so the static files can load properly but apparently 01_{{ card_id }}.jpg is not working as intended. I also tried to changing one of my image name from 01_01.jpg into 01.jpg and do the following:

>img src="{% static '/static_dirs/images/itcg/{{card_id}}.jpg' %}" alt="{{ card_id }}">

The image still not loading, so I guess the problem is not in "01_" part either. Can someone help?

The {{ .. }} embedded within a {% ... %} doesn't look good. Write like this:

img src="{% static '/static_dirs/images/itcg' %}/{{ card_id }}.jpg" alt="{{ card_id }}">

That is, this will get the correct base url for the static image (the directory), and then you simply append the rest of the image file name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM