Skip to content
Advertisement

Set URL to load iframe in a Django template

I want to load an 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:

<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, but it doesn’t load. In its place, the parent template itself appears. I looked around Stack Overflow, and from some of the posts I gather that I need to set the src attribute of the iframe to a Django view, which will load the iframe separately. Is this correct? If so, how do I configure the URL (i.e. set the path to the view)?

Advertisement

Answer

Yes, you have to create the view to load the template. The simplest way to do this is to use generic TemplateView. Add this url to urlpatterns in your 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 id="encoder_iframe" height=75% width="50%" src="{% url 'testgame' %}">
</iframe>
                   
Advertisement