javascript 设置 URL 以在 Django 模板中加载 iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28268574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:41:51  来源:igfitidea点击:

Set URL to load iframe in a Django template

javascripthtmldjangoiframe

提问by user3033194

I want to load a iframe into a Django template. The template is getting loaded correctly, but in place of the iframe, the template itself is getting embedded inside the parent template. The code relevant is given below:

我想将 iframe 加载到 Django 模板中。模板被正确加载,但代替 iframe,模板本身被嵌入到父模板中。相关代码如下:

        <body>

                <p>
                        <strong>Player: {{player.username}}</strong>&nbsp;
                        <div id="playerid">{{player.id}}</div><br>
                        <iframe id="encoder_iframe" height=75% width="50%" src="testgame.html"></iframe>
                        <br>
                        <strong>Last score:</strong>&nbsp;
                        <span id="scores"></span><br><br>
                        <strong>Game state:</strong>
                        <div id="gamestate"></span>
                </p>
                <br>
        </body>

"testgame.html" is a file located in the same directory as this HTML template itself, but it doesn't load. In its place, the parent template itself appears. I looked in this forums, and from some of the posts I gather that I need to set the "src" attribute of "iframe" to a Django view, which will load the iframe separately. Is this correct? If so, how do I name the URL (i.e. set the path to the view)?

“testgame.html”是与此 HTML 模板本身位于同一目录中的文件,但它不会加载。取而代之的是父模板本身。我查看了这个论坛,从我收集的一些帖子中,我需要将“iframe”的“src”属性设置为 Django 视图,这将单独加载 iframe。这个对吗?如果是这样,我如何命名 URL(即设置视图的路径)?

I would be glad if you helped me with this. Thanks!!

如果你能帮我解决这个问题,我会很高兴。谢谢!!

回答by catavaran

Yes, you have to create the view to load the template. The simplaset way to do it is to use generic TemplateView. Add this url to urlpatternsin your urls.py:

是的,您必须创建视图来加载模板。这样做的简单方法是使用通用的TemplateView。将此网址添加到urlpatterns您的urls.py

from django.views.generic import TemplateView

url(r'^testgame/', TemplateView.as_view(template_name="testgame.html"),
                   name='testgame'),

And <iframe>tag will look like:

<iframe>标签的样子:

<iframe id="encoder_iframe" height=75% width="50%" src="{% url 'testgame' %}">
</iframe>