Django:将图像插入路径为动态的模板中 [英] Django: Insert image in a template whose path is dynamic
问题描述
我知道我可以使用以下模板在HTML生成的页面中插入一个图像:
< img src = {%staticmyapp / my_image.jpg%}alt =图像描述>
问题是我想要的东西稍微复杂一点。假设我的模板中有一个对象user,其中包含一个user.first_name和一个user.last_name属性。我想插入一个路径为:
< img src ={%staticmyapp / {{ user.first_name}} _ {{user.last_name}}。jpg%}alt =配置文件图片>
此行错误,我收到错误(Django无法解析表达式)。有人可以帮忙吗?
我正在搭建照片的组织图,是为每位会员提供个人资料图片的正确方法(根据事实上的图片应该被命名为firstname_lastname.jpg)?
谢谢
你将不得不使用自定义过滤器(不要使用添加
,这不意味着添加字符串)。
< img src ={%static'myapp /'| addstring:user.first_name | addstring:'_'| addstring:user.last_name | addstring:'。jpg'%}alt =配置文件图片>
您的自定义过滤器 addstring
可以
#In:templatetags /< app> _extras.py
/ pre>
from django import template
register = template.Library()
@ register.filter
def addstring(s1,s2):
return str(s1)+ str(s2)
另一个选择是拥有一个自定义过滤器,所有的魔法&在img src中使用它:
@ register.filter
def imgsrc(user):
return' myapp / {} _ {} jpg'.format(user.first_name,user.last_name)
I know I can insert an image in an html generated page based on a template using:
<img src="{% static "myapp/my_image.jpg" %}" alt="Image Description">
The problem is I want something slightly more complex. Let's say I have an object "user" in my template with a user.first_name and a user.last_name attributes. I would like to insert an image whose path would be:
<img src="{% static "myapp/{{user.first_name}}_{{user.last_name}}.jpg" %}" alt="Profile Picture">
This line is wrong, I get an error (Django can't parse the expression). Can someone help?
I am building kind of a organization chart with photographs, is that a proper way of including profile pictures for every member (based on the fact that the pictures should be named firstname_lastname.jpg)?
Thanks
解决方案You'll have to use a custom filter (don't use
add
, that's not meant for adding strings).<img src="{% static 'myapp/'|addstring:user.first_name|addstring:'_'|addstring:user.last_name|addstring:'.jpg' %}" alt="Profile Picture">
Where your custom filter
addstring
could be# In : templatetags/<app>_extras.py from django import template register = template.Library() @register.filter def addstring(s1, s2): return str(s1) + str(s2)
Another option is having a custom filter do all the magic & use that in img src:
@register.filter def imgsrc(user): return 'myapp/{}_{}.jpg'.format(user.first_name, user.last_name)
这篇关于Django:将图像插入路径为动态的模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!