如何实现模板过滤器clean_url移除URL中域名前的所有字符?
实现Django模板过滤器
clean_url移除URL中网站名称前的所有字符 嘿,这需求我熟!我给你准备了两种实现方案,其中用Python内置URL解析库的方法最靠谱,能搞定各种复杂URL场景,先看这个:
推荐方案:用urllib.parse解析URL(健壮性拉满)
这个方法专门针对URL结构做处理,能完美应对http/https协议、带www前缀、带查询参数/锚点的各种情况,完全符合你的需求:
from urllib.parse import urlparse from django import template register = template.Library() @register.filter(name='clean_url') def clean_url(url): # 解析URL成各个组成部分 parsed_url = urlparse(url) # 处理域名:去掉开头的www.前缀 netloc = parsed_url.netloc if netloc.startswith("www."): netloc = netloc[4:] # 拼接域名+路径 cleaned_result = f"{netloc}{parsed_url.path}" # 如果有查询参数(比如?key=value),加上 if parsed_url.query: cleaned_result += f"?{parsed_url.query}" # 如果有锚点(比如#section1),加上 if parsed_url.fragment: cleaned_result += f"#{parsed_url.fragment}" # 处理非完整URL的情况(比如相对路径),直接返回原URL if not parsed_url.netloc: return url return cleaned_result
测试效果:
- 输入:
https://stackoverflow.com/questions/ask→ 输出:stackoverflow.com/questions/ask - 输入:
http://www.samsung.com/au/→ 输出:samsung.com/au/ - 输入:
https://www.example.com/page?foo=bar#top→ 输出:example.com/page?foo=bar#top
简化方案:字符串直接替换(适合简单场景)
如果你的URL只会是http/https开头,不会有其他协议,也不需要处理查询参数/锚点,用这个更简单:
from django import template register = template.Library() @register.filter(name='clean_url') def clean_url(url): # 先移除http://或https://前缀 cleaned = url.replace("https://", "").replace("http://", "") # 再移除开头的www. if cleaned.startswith("www."): cleaned = cleaned[4:] return cleaned
模板使用步骤:
- 在你的Django app里创建
templatetags文件夹(记得加__init__.py空文件) - 把上面的代码存成
templatetags/custom_filters.py - 在模板开头加载过滤器:
{% load custom_filters %} - 就可以用啦:
{{ url|clean_url }}
内容的提问来源于stack exchange,提问作者Zorgan
相关产品推荐
相关产品推荐

