django - Django OVERRIDE default templatetags
问题描述
I want to make {% url %} fail silently if no reverse match is found and just output a simple '#' or default homepage link.
How can I accomplish this without adding {% load tags %}
to my 100s of HTMLs? Kind of like monkey-patching but something production-ready.
解决方案
这应该可以,在任何看起来像这样的应用程序中创建一个名为“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
推荐阅读
- css - @media 规则在 Chrome 响应式设计模式下表现异常
- sql - 如何在 SQL 中用数字对字符串进行数字排序?
- python - 在 Ubuntu 16 Python3 上安装 TA-Lib 时出错
- python-3.x - 如何摆脱模块 python 安装中的 x86_64-linux-gnu-gcc 错误
- tensorflow - tensorflow“数据流图”的解释
- javascript - 是否有任何理论方法(一般规则)可以找出哪个脚本是最佳的并且加载速度更快?
- javascript - 从 ajax 获取时加载表单对象
- python - 打印不带括号的 Numpy 数组
- excel - Range().value="=(if) ... " 在 Excel 中
- mysql - 我应该从经常更新的表中的长 sql 查询中得到什么结果?