如何在<img src>中添加django模板变量? [英] How to add django template variable in <img src>?

查看:50
本文介绍了如何在<img src>中添加django模板变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个字段的照片模型:

I have a Photo model with two fields:

title = models.CharField()
path = models.CharField()

当我在管理面板中添加新照片时,路径等于 /images/image_ex.jpg 这是我的视图文件:

When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file:

def gallery(request):
   photos = Photo.objects.all()
   return render(request, 'gallery.html', {'photos': photos})

这是gallery.html中的标签:

This is the tag in gallery.html:

{% loadstaticfiles %}
<img src="{%static '{{photo.path}}'%}"/>

问题是照片没有渲染,如果我查看页面的代码,src 就是这样的:

The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that:

src="static/%7B%7B%20photo.path%20%7D%7D"

有什么问题?如何在 src 中使用模板变量?附言图像文件夹存在于静态文件夹中,图像也存在.我将静态目录添加到 settings.py.此外,如果我将 src 更改为普通的,例如

What is the problem? How can I use template variables in src? P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like

<img src="{static 'images/image_ex.png'%}">

照片渲染正常.

推荐答案

你在这里将 '{{photo.path}}' 作为 string 传递给 {% static ... %},因此它会简单地将静态 URL 根添加到此字符串.

You here pass '{{photo.path}}' as a string to {% static ... %}, hence it will simply prepend the static URL root to this string.

如果要使用photo.pathcontent,可以使用:

If you want to use the content of photo.path, you can use:

<img src="{% static photo.path %}"/>

所以{% static ... %} 接受变量作为参数,并且会取photopath属性的内容多变的.(当然,如果传递了变量,或者是您使用 {% for ... %} 循环等生成的变量.

So {% static ... %} accepts variables as parameters, and will take the content of the path attribute of the photo variable. (of course given that variable is passed, or is a variable you generate with {% for ... %} loops, etc.

这篇关于如何在&lt;img src&gt;中添加django模板变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆