generate iframe from django tag

2019-09-13 02:46发布

问题:

I managed to create a REST api with multiple items like this

{
    "title": "problem_demo.0",
    "html": "<div><iframe src=/scenario/problem_demo.0/ width=\"400\" height=\"500\"></iframe></div>",
    "description": "desc",
    "url": "/scenario/problem_demo.0/"
},

And i managed to extract some data and render them in my template like this

views.py

if embedserializer.is_valid():
       embed = embedserializer.validated_data
       return render(request, 'workbench/dir/xblock.html', 
       {'embed': embed})

xblock.html

% block content %}

<ul>
    <li>title : {{ embed.title}}</li>
    <li>description: {{ embed.description }}</li>
    <li>html : {{ embed.html }}</li>
    <li>url : {{ embed.url }}</li>

</ul>


{% endblock %}

What i want is to be able to get an actual iframe when i add {{ embed.html }} in my template and not the value of the key "html".

回答1:

You want safe - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe

<li>html : {{ embed.html|safe }}</li>