Chris
Chris

Reputation: 5814

How to display html from the controller in the view using Web2Py?

I'm utilizing web2py and I'd like to display html code that is returned from a python function in the controller.

I have the following controller (default.py):

def index():
     return {"html_code":"<img src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017'>"}

This is my view (index.html):

{{=html_code}}

When I visit the site (http://127.0.0.1:8000/test/default/index), I see the following (instead of the image)

<img src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017'>

How can I render the variable called html_code as html instead of as plain text?

Upvotes: 1

Views: 2757

Answers (2)

Anthony
Anthony

Reputation: 25536

By default, any content written to the view via {{=...}} is escaped. To suppress the escaping, you can use the XML() helper:

{{=XML(html_code)}}

Alternatively, you can construct the HTML via the server-side HTML helpers rather than generating raw HTML:

def index():
     return {"html_code": IMG(_src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017')}

And then you can leave the view as you have it:

{{=html_code}}

The above assumes that you are generating the HTML via your own code. If the HTML in question comes from an untrusted source (e.g., user input), writing it to the view without escaping presents a security risk. In that case, you can have the XML() helper doing some sanitizing (i.e., it will limit the allowed HTML tags and attributes to a safe whitelist) (see here for more details):

{{=XML(html_code, sanitize=True)}}

Upvotes: 2

Tomek Krasuski
Tomek Krasuski

Reputation: 41

try use XML() helper

def index():
return {"html_code":XML("<img src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017'>")}

Upvotes: 0

Related Questions