在格式化纯文本时,如何让python-markdown另外“urlify”链接?

时间:2008-10-15 06:22:22

标签: python django markdown

Markdown是一个很好的工具,用于将纯文本格式化为漂亮的HTML,但它不会自动将纯文本链接转换为URL。像这样:

http://www.google.com/

格式化文本块时,如何在网址上添加标记?

7 个答案:

答案 0 :(得分:5)

您可以为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

但是谁还想这样做呢?!

答案 1 :(得分:3)

最佳案例场景,编辑降价,然后将&lt; &GT;围绕URL。这将使链接可以点击。唯一的问题是它需要教育您的用户,或者写下降价的人。

答案 2 :(得分:2)

这不是Markdown的一项功能 - 您应该做的是针对文本运行后处理器以寻找类似URL的模式。 Google app engine example code中有一个很好的示例 - 请参阅AutoLink转换。

答案 3 :(得分:2)

我使用的是Django framework,它有一个名为urlize的过滤器,它完全符合我的要求。但是,它只适用于纯文本,所以我无法通过markdown的输出。我按照this guide创建了一个名为urlify2的自定义过滤器,该过滤器适用于html,并通过此过滤器传递文本:

<div class="news_post">
  {% autoescape off %}
    {{ post.content|markdown|urlify2}}
  {% endautoescape %}
</div>

urlify2.py过滤器:

from django import template
import re

register = template.Library()

urlfinder = re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+):[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]")

@register.filter("urlify2")
def urlify2(value):
    return urlfinder.sub(r'<a href="\1">\1</a>', value)

答案 4 :(得分: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>

答案 5 :(得分:1)

在python-markdown2中还有一个额外的内容:

http://code.google.com/p/python-markdown2/wiki/LinkPatterns

答案 6 :(得分:1)

我知道这个问题已经差不多十年了,但是markdown-urlize涵盖了我能想到的每一个可能的用例,包括不需要http(s)://在url之前,将括号留在public中,从r2.setAveragePrice(r1.getAveragePrice()); r2.setPeopleServed(r1.getPeopleServed()); 中移除尖括号,忽略代码块中的网址,以及我没有想到的更多:

https://github.com/r0wb0t/markdown-urlize

没有pip安装,但你可以这样做:

https://raw.githubusercontent.com/r0wb0t/markdown-urlize/master/mdx_urlize.py

然后将上面的文件放在python路径(第一个选项)或不是(第二个选项),然后使用以下之一:

(google.com)