如何让python-markdown在格式化纯文本时额外“urlify”链接?
Markdown 是一个很棒的工具,可以把普通文本格式化成漂亮的 HTML 页面,但它不会自动把普通文本链接变成网址链接。比如说这个链接:
那么,我该怎么做才能让 Markdown 在格式化一段文本时,自动给网址加上链接标签呢?
7 个回答
4
最理想的情况是,编辑一下markdown格式,把网址前后加上< >符号。这样链接就变得可以点击了。唯一的问题是,这需要让你的用户或者写markdown的人了解这个规则。
6
你可以为markdown写一个扩展。把下面的代码保存为mdx_autolink.py
import markdown
from markdown.inlinepatterns import Pattern
EXTRA_AUTOLINK_RE = r'(?<!"|>)((https?://|www)[-\w./#?%=&]+)'
class AutoLinkPattern(Pattern):
def handleMatch(self, m):
el = markdown.etree.Element('a')
if m.group(2).startswith('http'):
href = m.group(2)
else:
href = 'http://%s' % m.group(2)
el.set('href', href)
el.text = m.group(2)
return el
class AutoLinkExtension(markdown.Extension):
"""
There's already an inline pattern called autolink which handles
<http://www.google.com> type links. So lets call this extra_autolink
"""
def extendMarkdown(self, md, md_globals):
md.inlinePatterns.add('extra_autolink',
AutoLinkPattern(EXTRA_AUTOLINK_RE, self), '<automail')
def makeExtension(configs=[]):
return AutoLinkExtension(configs=configs)
然后在你的模板中这样使用它:
{% load markdown %}
(( content|markdown:'autolink'))
更新:
我发现这个解决方案有个问题:当使用markdown的标准链接语法时,如果显示的部分符合某个规则,比如:
[www.google.com](http://www.yahoo.co.uk)
就会奇怪地变成: www.google.com
不过,谁会想这样做呢?!
2
我没法让superjoe30的正则表达式正常工作,所以我对他的解决方案进行了调整,使普通的URL(在Markdown文本中)变得可以和Markdown兼容。
修改后的过滤器:
urlfinder = re.compile('^(http:\/\/\S+)')
urlfinder2 = re.compile('\s(http:\/\/\S+)')
@register.filter('urlify_markdown')
def urlify_markdown(value):
value = urlfinder.sub(r'<\1>', value)
return urlfinder2.sub(r' <\1>', value)
在模板中:
<div>
{{ content|urlify_markdown|markdown}}
</div>