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

查看:58
本文介绍了如何在< 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中使用模板变量?P.S.images文件夹存在于静态文件夹中,图像也存在.我将静态目录添加到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.path content ,可以使用:

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

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

因此, {%static ...%} 接受变量作为参数,并将采用 photo path 属性的内容多变的.(当然,如果已传递变量,或者是使用 {%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天全站免登陆