Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试在Django中编写自定义模板标记,以在文本中查找电话号码并将其转换为链接_Django_Django Templates_Wagtail - Fatal编程技术网

尝试在Django中编写自定义模板标记,以在文本中查找电话号码并将其转换为链接

尝试在Django中编写自定义模板标记,以在文本中查找电话号码并将其转换为链接,django,django-templates,wagtail,Django,Django Templates,Wagtail,我想将这个字符串tel:123-456-7890.1234转换为html中的a链接。最终输出将是 我对Regex不太在行,而且我很接近,但我需要一些帮助。我知道我并没有完全掌握正则表达式和输出。我如何改变我必须要做的,使它工作 import re @register.filter(name='phonify') @stringfilter def phonify(val): """ Pass the string 'tel:1234' to the filter and the

我想将这个字符串
tel:123-456-7890.1234
转换为html中的
a
链接。最终输出将是

我对Regex不太在行,而且我很接近,但我需要一些帮助。我知道我并没有完全掌握正则表达式和输出。我如何改变我必须要做的,使它工作

import re

@register.filter(name='phonify')
@stringfilter
def phonify(val):
    """
    Pass the string 'tel:1234' to the filter and the right tel link is returned.
    """
    # find every instance of 'tel' and then get the number after it
    for tel in re.findall(r'tel:(\d{3}\D{0,3}\d{3}\D{0,3}\d{4})\D*(\d*)', val):
        # format the tag for each instance of tel
        tag = '<a href="tel:{}">{}</a>'.format(tel, tel)
        # replace the tel instance with the new formatted html
        val = val.replace('tel:{}'.format(tel), tag)
    # return the new output to the template context
    return val
重新导入
@register.filter(name='phonify')
@细滤器
def语音(val):
"""
将字符串“tel:1234”传递给筛选器,然后返回正确的tel链接。
"""
#找到“tel”的每一个实例,然后在它后面找到号码
对于re.findall(r'tel:(\d{3}\d{0,3}\d{3}\d{0,3}\d{4})\d*(\d*),val)中的电话:
#设置每个tel实例的标记格式
标签=''。格式(电话,电话)
#用新的格式化html替换tel实例
val=val.replace('tel:{}'。格式(tel),标记)
#将新输出返回到模板上下文
返回值

我添加了wagtail标记,因为我在wagtail中看到了其他解决方案,这是wagtail所需要的,因此这可能对其他人有帮助。

您可以使用
re.sub
执行查找和替换:

import re

@register.filter(name='phonify')
@stringfilter
def phonify(val):
    tel_rgx = r'tel:(\d{3}\D{0,3}\d{3}\D{0,3}\d{4}\D*\d*)'
    return re.sub(tel_rgx, r'<a href="tel:\1">\1</a>', val)

不管您如何做,它都会将所有项目标记为安全的,甚至是标记等,它们是原始字符串的一部分,因此应该转义。因此,我不确定这是否是一个好主意。

您可以使用
re.sub
执行查找和替换:

import re

@register.filter(name='phonify')
@stringfilter
def phonify(val):
    tel_rgx = r'tel:(\d{3}\D{0,3}\d{3}\D{0,3}\d{4}\D*\d*)'
    return re.sub(tel_rgx, r'<a href="tel:\1">\1</a>', val)
不管您如何做,它都会将所有项目标记为安全的,甚至是标记等,它们是原始字符串的一部分,因此应该转义。因此,我不确定这是一个好主意