I'm working in web2py and I'm trying to print out html code from the controller, which is written in python. The issue is even when I write the html in a string in python, the page is rendering this string as it would normal html. This seems like there would be a simple fix, but I have not been able to find an answer. Here is the specific code.
return ('Here is the html I'm trying to show: <img src= {0}>'.format(x))
The resulting page shows "Here is the html I'm trying to show: " and then the rest is blank. If I inspect the page the rest of the code is still there, which means it is being read, just not displayed. So I just need a way to keep the html that is in the string from being interpreted as html. Any ideas?
If you want to send HTML markup but have the browser treat it and display it as plain text, then simply set the HTTP Content-Type
header appropriately. For example, in the web2py controller:
def myfunc():
...
response.headers['Content-Type'] = 'text/plain'
return ("Here is the html I'm trying to show: <img src={0}>".format(x))
On the other hand, if you want the browser to treat and render the response as HTML and you care only about how it is displayed in the browser (but not about the actual text characters in the returned content), you can simply escape the HTML markup. web2py provides the xmlescape
function for this purpose:
def myfunc():
x = '/static/myimage.png'
html = xmlescape("<img src={0}>".format(x))
return ("Here is the html I'm trying to show: {0}>".format(html))
The above will return the following to the browser:
Here is the html I'm trying to show: <img src=/static/myimage.png>
which the browser will display as:
Here is the html I'm trying to show: <img src=/test/image.png>
Note, if you instead use a web2py template to generate the response, any HTML markup inserted will automatically be escaped. For example, you could have a myfunc.html
template like the following:
{{=markup}}
And in the controller:
def myfunc():
...
return dict(markup="Here is the html I'm trying to show: <img src={0}>".format(x))
In that case, web2py will automatically escape the content inserted via {{=markup}}
(so no need to explicitly call xmlescape
).