首页 > 解决方案 > 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.

标签: djangodjango-templates

解决方案


这应该可以,在任何看起来像这样的应用程序中创建一个名为“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


推荐阅读