我有一个普通的应用程序,其目录结构类似于以下内容:
...static/
Training/
css/
img/
js/
...templates/
....
在我的一个模板中,我想从数据库中获取图像名称并构建图像的路径。例如,如果我有图像 MyPicture.jpg,那么我想包含静态并将其与“Training/img/”和文件名结合起来得到类似
'..path to static../Training/img/MyPicture.jpg'
我找到了以下建议使用模板标签的文章,所以我尝试了这个:
from django import template
register = template.Library()
@register.filter
def addstr(arg1, arg2):
# Apparently, add has side effects, so use this:
# https://stackoverflow.com/questions/4386168/how-to-concatenate-strings-in-django-templates
return str(arg1) + str(arg2)
使用模板:
{% with static|addstr:"Training/img/"|addstr:course.img as imgpath %}
<img class="card-img rounded-lg rounded-top" src="{{ imgpath }}" alt="Card image">
{% endwith %}
不幸的是,这忽略了地址的静态部分。
如何结合所有三个部分?
[ps 我在模板顶部有一个 {% load static %} ]
谢谢
标记