【问题标题】:using a variable as an image source in html? (python)在html中使用变量作为图像源? (Python)
【发布时间】:2014-11-22 19:08:21
【问题描述】:

在我开始之前,请原谅我的英语,HTML 新手,这是我正在创建的第一个 django 应用程序。

假设我想根据表单中的输入查看静态图像以进行测试,所以如果我输入表单 goat.jpg 它将显示 goat.jpg

这是我的html

<!DOCTYPE html>

{% load static %}

<html>

<head>
    <title>test</title>
</head>

<body>
    <center><img src="{% static "{{staticpath}}" %}" alt="gif" align="middle"/></center>
    {{boldmessage}}

这是我的看法

from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

def generate(request):
    context = RequestContext(request)
    if request.GET:
        path = request.GET.get('path','')
    context_dict = {'staticpath':path}
    return render_to_response("generated/generated.html", context_dict, context)

path 已经是一个字符串,但是如果我删除 staticpath 双引号 django 会引发异常。那么如何将路径的字符串准确地放入 html 图像源中,以便正确显示静态图像呢?谢谢!

【问题讨论】:

    标签: python html django image


    【解决方案1】:

    调用 {% static 'some/path/' %} 将调用 Django static file finders。如果您要查找的图像在一个目录中,并且您只将文件名传递给 {% static 'some/path' %} 它不会找到该文件。

    了解 {{ STATIC_URL }} 标签作为避免嵌套标签的解决方案。如果您的文件都存储在 staticfiles 目录的根文件夹中(由 settings.py 中的 STATIC_ROOT 设置设置),那么这将起作用- &lt;img src="{{ STATIC_URL }}{{ staticpath }}"/&gt; 但是,最好实现一个由您的视图调用的函数,该函数搜索您的 STATIC_ROOT 文件夹和所有子文件夹,以找到文件的完整相对(到 STATIC_ROOT )路径并返回它。这种方法很复杂,但会奏效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多