Django Template Language - getting url encoded values

允我心安 提交于 2019-12-04 05:43:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!