【问题标题】:Django OVERRIDE default templatetagsDjango OVERRIDE 默认模板标签
【发布时间】:2019-01-13 06:12:08
【问题描述】:

如果没有找到反向匹配,我想让 {% url %} 静默失败,只输出一个简单的 '#' 或默认主页链接。

如何在不将{% load tags %} 添加到我的 100 多个 HTML 的情况下完成此操作?有点像猴子补丁,但可以用于生产。

【问题讨论】:

标签: django django-templates


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    正如 cmets 中所述,这不是您通常想要做的事情。但是,一种方法是使用变量:

    {% url "some:url" as the_url %}
    {{ the_url|default:"#"}}
    

    这也可以写在一行上:

    <a href="{% url "some:url" as the_url %}{{ the_url|default:"#"}}">...</a>
    

    【讨论】:

    • 谢谢,但是这会造成成千上万的变化这是一个巨大的项目,所以它并不真正可行。
    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 2011-11-27
    • 2021-02-18
    • 1970-01-01
    • 2011-02-09
    • 2013-03-15
    • 2012-10-31
    相关资源
    最近更新 更多