问题描述
我想从python Django传递一个变量,并在<img>
标记内使用它.我该怎么做?
I want to pass a variable from python Django and use it inside the <img>
tag. How can I do it?
这是我的代码.
Python-
render(request, 'dashboard/dashboard.html', {"variable_int" : 12})
HTML
<img src="{% static "img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}" /></td>
我知道我需要在{{}}
之间传递它,但是我没有得到图像.我该怎么办?
I know that I need to pass it between {{}}
but I'm not getting the image. How can I do it?
推荐答案
问题是Django首先转换url,然后在代码上没有任何变量.
The problem is django first convert the url, and then you don't have any variable on the code.
Django对此进行更改:
Django change this:
{% static "img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}
为此:
"/static/img/icons/vendor/yahoo_weather/%7B%7Bvariable_int%7D%7D.gif"
Django首先调用函数"以获取静态网址,然后更改其中的所有代码.您可以尝试调用变量{{STATIC_URL}}(如果您在settings.py上定义了该变量),则该变量将获取静态文件夹的路径,然后将获取该变量的值.
Django first call the "function" to get static urls, and change all the code inside. You can try to call a variable {{ STATIC_URL }} (if you have it defined on settings.py), that variable will get the path for the static folder, and after it will get the value of the variable.
尝试一下:
<img src="{{ STATIC_URL}}img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}" /></td>
在这种情况下,django应该进行2次更改,{{STATIC_URL}}和{{variable_int}}而不是仅进行一次更改.
In this case django should make 2 changes, {{ STATIC_URL}} and {{variable_int}} instead of just one.
这篇关于如何将变量从python Django传递到HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!