问题
I'm using Django Template language, using load staticfiles. However when I do the following
<img src="{% static 'img/category/{{category.category|lower|slugify}}.jpg' %}">
I get the HTML as
<img src="/static/img/category/%7B%7Bcategory.category%7Clower%7Cslugify%7D%7D.jpg">
which obviously is not rendering the correct image.
However my expected output was
<img src="/static/img/category/electronics.jpg">
where category.category = electronics
I'm passing category as a ctx variable. Why is it happening like this?
回答1:
You can't have a variable in the static tag, that's why you see these %7B%7B in your HTML output.
You can however do this:
{% load static %}
<img src="{% get_static_prefix %}img/category/{{category.category|lower|slugify}}.jpg">
回答2:
First of all - shouldn't that image be served from media files? Static files are not designed to be connected with models, that's what media files are for.
Secondly - you can't use variables syntax inside other tags in django. Unless tag is designed to take some parameters, you can't pass them into.
来源:https://stackoverflow.com/questions/32167517/django-template-language-getting-url-encoded-values