1.正则表达式

\blog\home\templatetags\comment_tags.py

 

@register.filter(name='regexp')
def regexp(value):
    # 分割获取第一个url
    catalog_list = re.compile('name="(\\d+.*?)"', re.S).findall(value)
    lis = []
    for k in catalog_list:
        four = re.compile('(^\\d+.\\d+.\\d+.\\d+.*?)', re.S).findall(k)
        three = re.compile('(^\\d+.\\d+.\\d+.*?)', re.S).findall(k)
        two = re.compile('(^\\d+.\\d+.*?)', re.S).findall(k)
        if four:
            lis.append(k)
        elif three:
            lis.append(k)
        elif two:
            lis.append(k)
        else:
            lis.append(k)

    if lis:
    # print(a)
        return " ".join(lis)

则测名字和comment_tags里面注册名字一样

\blog\templates\index.html 

{% load comment_tags %}
                                    <p style="color: gray;" >
                                        {{ article.sumary }}
                                        {% with article.content|safe|regexp as path %}
                                            {% if path %}
                                                {{ path }}
                                            {% else %}
                                                {{ article.content | striptags | truncatechars_html:100 }}
                                            {% endif %}
                                        {% endwith %}

                                    </p>

2.字符分割

\blog\diary\templatetags\home_tags.py

@register.filter(name='split')
def split(value, arg):
    # 分割获取第一个url
    for path in value.split(arg):
        if path:
            # print(path)
            return path

\blog\templates\diary\nav.html

{% load home_tags %}

{% with request.path|split:"/" as path %}
            {# tag里面分割取得第一个,传到这里#}
            <form class="form-inline my-2 my-lg-0" action="
                    {% if path == "yys"  %}{% url 'diary:search' %}
                  method="get">
                <input class="form-control mr-sm-2" type="search"
                       style="background: rgba(255,255, 255, 0.6);color: black" name="q" placeholder="Search"
                       aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0 " type="submit">搜索</button>
            </form>
{% endwith %}