英文:
How to pass link to file in Django views
问题
以下是代码的翻译部分:
在“task1.html”文件中,你可以这样显示图片:
<figure><img src={% static '{{ main_figure }}' %}></figure>
<p>{{ description }}</p>
在“views.py”文件中,你的视图函数如下:
def task1(request):
return render(
request,
"App/Tasks/task1.html",
{
'main_figure' : "assets/placeholder_img.png",
'description' : "Placeholder image and text"
}
)
如果图片没有显示,可能是视图函数的问题。你尝试了不同的方式传递图片路径,但都没有成功。希望这有所帮助。
英文:
I am very new to Django and trying display an image on an html page by passing the path to the src from the view.
I have this in the 'task1.html' file
<figure><img src={% static '{{ main_figure }}' %}></figure>
<p>{{ description }}</p>
and this in the 'views.py' file
def task1(request):
return render(
request,
"App/Tasks/task1.html",
{
'main_figure' : "assets/placeholder_img.png",
'description' : "Placeholder image and text"
}
)
But the image does not show. If I remove the 'main_figure' : "assets/placeholder_img.png",
line and change
<figure><img src={% static '{{ main_figure }}' %}></figure>
to <figure><img src={% static 'assets/placeholder_img.png' %}></figure>
the image displays, so the issue seems to be with the views function.
I have tried passing different parts of the src from the view, e.g.
<img src={{ main_figure }}>
with 'main_figure' : "{% static 'assets/placeholder_img.png' %}",
and
<img src={% static 'assets/{{ main_figure }}.png' %}>
with 'main_figure' : "placeholder_img",
but it always shows the little image not found icon.
Any help would be greatly appreciated, thanks very much.
答案1
得分: 1
-
{{xxx}}只是打印变量xxx(即{{}}中的内容),因此不需要空格。
-
{% xxx %}执行一个标签,%前后需要空格。
-
如果需要在标签内使用变量,不需要使用{{}}:{% static main_figure %}
英文:
-
{{xxx}} is just printing a variable xxx (so what is inside {{ }}) therefore no spaces are needed.
-
{% xxx %} is executing a tag and spaces before/after % are necessary
-
if you need to use a variable inside tag no need to use {{ }}: {% static main_figure %}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论