linkify函数:
属于 tornado.escape,用于将设定的text修改为链接方式,其格式如下:
linkify(text, shorten=False, extra_params='', require_protocol=False, permitted_protocols=['http', 'https'])
For example: linkify("Hello http://tornadoweb.org!") would return
Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!
Parameters:
shorten: Long urls will be shortened for display.
extra_params: Extra text to include in the link tag, e.g. linkify(text, extra_params='rel="nofollow" class="external"')
require_protocol: Only linkify urls which include a protocol. If this is False, urls such as www.facebook.com will also be linkified.
permitted_protocols: List (or set) of protocols which should be linkified, e.g. linkify(text, permitted_protocols=["http", "ftp", "mailto"]).It is very unsafe to include protocols such as "javascript".
以下是一些在Tornado模板中测试的内容
{%raw linkify("check it out http://www.baidu.com")%}
浏览器中渲染的结果是:
"check it out"<a href="http://www.baidu.com">www.baidu.com</a>
去掉linkify中的http://
{%raw linkify("check it out www.baidu.com")%}
浏览器中渲染的结果是:
"check it out"<a href="http://www.baidu.com">www.baidu.com</a>
可见会自动添加上http://
保留linkify中的http://但去掉www
{%raw linkify("check it out http://baidu.com")%}
浏览器中渲染的结果是:
"check it out"<a href="http://baidu.com">baidu.com</a>
将linify中的http://更换为mailto 或 ftp
{%raw linkify("check it out ftp://baidu.com")%}
浏览器中渲染的结果是:
"check it out ftp://baidu.com" 一段纯文本
将linkify中的内容更换为HTML标签
{%raw linkify("check it out <a href='baidu.com'><p>xxx</p></a>")%}
浏览器中渲染的结果是:
"check it out <a href='baidu.com'><p>xxx</p></a>" 一段纯文本
将linkify中的内容更换为HTML标签,只不过这次href写成www.baidu.com
{%raw linkify("check it out <a href='baidu.com'><p>xxx</p></a>")%}
浏览器中渲染的结果是:
"check it out <a href="<a href="http://www.baidu.com">www.baidu.com</a>"<p>xxx</p></a>"
一段混合了超链接和文本的内容
所以,linkify对http和www关键字敏感
另外,模板中linkify关键字要与raw连用,否则无论哪种写法客户端浏览器访问时就会产生500错误
另外也有关于raw在模板中使用的一些小例子:
{% set mailLink = '<a href="mailto:contact@burtsbooks.com">Contact Us</a>' %}
{{mailLink}}<br>
{%raw mailLink%}<br>
{% set sp = '<script>alert("哈哈哈哈")</script>' %}
{{sp}}
{%raw sp%}在浏览器中的效果将是:
"<a href="mailto:contact@burtsbooks.com">Contact Us</a>" 对应{{mailLink}}的是纯文本显示一句话
<a href="mailto:contact@burtsbooks.com">Contact Us</a> 对应{%raw mailLink}的是一个超链接
"<script>alert("哈哈哈哈")</script>"对应{{sp}}的是纯文本显示一句话
<script>alert("哈哈哈哈")</script>对应{%raw sp%}的是一句JavaScript代码并且可以执行