【发布时间】:2019-01-13 06:12:08
【问题描述】:
如果没有找到反向匹配,我想让 {% url %} 静默失败,只输出一个简单的 '#' 或默认主页链接。
如何在不将{% load tags %} 添加到我的 100 多个 HTML 的情况下完成此操作?有点像猴子补丁,但可以用于生产。
【问题讨论】:
-
你为什么要这样做?您收到 NoReverseMatch 错误的唯一原因是模板中的错误。
如果没有找到反向匹配,我想让 {% url %} 静默失败,只输出一个简单的 '#' 或默认主页链接。
如何在不将{% load tags %} 添加到我的 100 多个 HTML 的情况下完成此操作?有点像猴子补丁,但可以用于生产。
【问题讨论】:
这应该有效, 在任何看起来像这样的应用程序中创建一个名为“builtins.py”的文件
from django import template
from django.template.defaulttags import url
from django.urls.exceptions import NoReverseMatch
register = template.Library()
def decorator(func):
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except NoReverseMatch:
return '#'
return wrap
@register.tag(name='url')
def custom_url(parser, tokens):
url_node = url(parser, tokens)
url_node.render = decorator(url_node.render)
return url_node
在您的settings.py 文件中
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'builtins': ['app_name.builtins'], # <-- Here
},
},
]
app_name 是您创建 builtins.py 的位置
【讨论】:
正如 cmets 中所述,这不是您通常想要做的事情。但是,一种方法是使用变量:
{% url "some:url" as the_url %}
{{ the_url|default:"#"}}
这也可以写在一行上:
<a href="{% url "some:url" as the_url %}{{ the_url|default:"#"}}">...</a>
【讨论】: