如果你想發送HTML標記,但有瀏覽器的對待它,並顯示它爲純文本,然後只需簡單地設置HTTP Content-Type
標題。例如,在web2py的控制器:
def myfunc():
...
response.headers['Content-Type'] = 'text/plain'
return ("Here is the html I'm trying to show: <img src={0}>".format(x))
在另一方面,如果您希望瀏覽器處理和呈現響應爲HTML,你只關心它是如何顯示在瀏覽器(但不是關於返回內容中的實際文本字符),您可以簡單地轉義HTML標記。的web2py提供用於此目的的xmlescape
功能:
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))
上面將返回以下到瀏覽器:
Here is the html I'm trying to show: <img src=/static/myimage.png>
該瀏覽器將顯示爲:
Here is the html I'm trying to show: <img src=/test/image.png>
請注意,如果您使用web2py模板生成響應,則任何HT插入的ML標記會自動轉義。例如,你可以有一個myfunc.html
模板類似如下:
{{=markup}}
和Controller:
def myfunc():
...
return dict(markup="Here is the html I'm trying to show: <img src={0}>".format(x))
在這種情況下,web2py中會自動跳脫通過{{=markup}}
插入內容(所以沒必要明確地呼叫xmlescape
)。
已經試過'r「這裏是我試圖顯示的html:」.format(x)'?否則[https://stackoverflow.com/a/2820547/6655211](https://stackoverflow.com/a/2820547/6655211) – PRMoureu