检查网址是否匹配模板 [英] Check if url matches in template
本文介绍了检查网址是否匹配模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
这是你想要的东西通常希望在一个views.py文件中使用反向()帮助具有已知参数的命名URL或解析 ()的路径。
如果您在模板中确实需要此功能,这里是一个恶意的解决方案:
@ register.simple_tag
def urlpath_exists(name):
为成功解析()'返回True
try :
return bool(resolve(path))
除了Resolver404:
返回False
注意:这并不能保证网址有效,只是出现了匹配模式。
Is it possible to check in template that some url match any pattern from urls?
解决方案
This is something you'd normally want to do in a views.py file with the reverse() helper for named URLs with known args or resolve() for paths.
If you do need this functionality in a template specifically, here is a hacky solution:
@register.simple_tag
def urlpath_exists(name):
"""Returns True for successful resolves()'s."""
try:
return bool(resolve(path))
except Resolver404:
return False
Note: this doesn't guarantee that the URL is valid, just that there was a pattern match.
这篇关于检查网址是否匹配模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文