我想从 python Django 传递一个变量并在 <img>
中使用它标签。我该怎么做?
这是我的代码。
Python-
render(request, 'dashboard/dashboard.html', {"variable_int" : 12})
HTML
<img src="{% static "img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}" /></td>
我知道我需要在 {{}}
之间传递它但我没有得到图像。我该怎么做?
最佳答案
问题是django先转换url,然后你代码上没有任何变量。
Django 改变这个:
{% static "img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}
为此:
"/static/img/icons/vendor/yahoo_weather/%7B%7Bvariable_int%7D%7D.gif"
Django首先调用“函数”获取静态url,并更改里面的所有代码。您可以尝试调用变量 {{ STATIC_URL }}(如果您在 settings.py 中定义了它),该变量将获取静态文件夹的路径,然后获取变量的值。
试试这个:
<img src="{{ STATIC_URL}}img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}" /></td>
在这种情况下,django 应该进行 2 处更改,{{ STATIC_URL}} 和 {{variable_int}} 而不是一个。
关于python - 如何将变量从 python Django 传递到 HTML 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19975480/