嵌入链接在硬编码时显示,但作为变量传递时不显示

问题描述 投票:0回答:1

当我尝试在我的页面中显示嵌入的谷歌地图链接时,我的 django 项目遇到以下问题。当我对 src URL 进行硬编码时,这是有效的(使用填充的地图渲染 Google 地图 iframe),但当我在上下文中传递它时,即使它们产生相同的文本字符串,它也不起作用。

这是我的html

detailview.html
:

        {% if maps_link is not None %}
          <iframe
            src="https://maps.google.com/maps?q=-28.4457436,21.268374&hl=en&z=14&amp;output=embed"            
            loading="lazy"
            referrerpolicy="no-referrer-when-downgrade"
          ></iframe>
        {% endif %}

上面显示的 src URL 按我想要的方式显示,但是当我执行以下操作时:

        {% if maps_link is not None %}
          <iframe
            src="{{ maps_link }}"    <!-- This gets blocked -->   
            loading="lazy"
            referrerpolicy="no-referrer-when-downgrade"
          ></iframe>
        {% endif %}

然后我的浏览器给我以下警告:

为了保护您的安全,如果其他网站嵌入了该页面,www.google.com 将不允许 Firefox 显示该页面。要查看此页面,您需要在新窗口中打开它。

这是我的

views.py
生成上下文的地方。我试图通过应用 xframes 豁免来解决这个问题,但这没有什么区别:

from django.views.decorators.clickjacking import xframe_options_exempt
from django.http import Http404, HttpResponse

@xframe_options_exempt
def detail(request, database_reference):
    try:
        obj = Consolidated.objects.get(database_reference=database_reference)
    except Consolidated.DoesNotExist:
        raise Http404("This database object does not exist: " + database_reference)

    context = {
        "content" : content_list,
        "maps_link": obj.location_link
    }

    print(context['maps_link'])
    print(type(context['maps_link']))

    template = loader.get_template("home/detailview.html")
    return HttpResponse(template.render(context, request))

print(context['maps_link'])
结果为
https://maps.google.com/maps?q=-25.797944,28.307176&hl=en&z=14&amp;output=embed

print(type(context['maps_link']))
产生以下类型
<class 'str'>

因此,打印出 {{maps_link}} 值会得到与硬编码 URL 完全相同的字符串。 有人可以告诉我为什么会发生这种情况(html 端硬编码的字符串和作为参数传递的字符串有什么区别),更重要的是我如何解决它?谢谢

python html django django-templates
1个回答
0
投票

在 HTML 中,

&amp;
自动转换为字符
&
。因此,网址

https://maps.google.com/maps?q=-28.4457436,21.268374&hl=en&z=14&amp;output=embed

其实是

https://maps.google.com/maps?q=-28.4457436,21.268374&hl=en&z=14&output=embed
.

但是,当 Django 进行替换时,它不会替换特殊序列

&amp;
。因此,访问的 URL 是不同的。

要解决此问题,您可以自行更换。更换

context = {
    "content" : content_list,
    "maps_link": obj.location_link
}

context = {
    "content" : content_list,
    "maps_link": obj.location_link.replace('&amp;', '&')
}

这应该可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.