Django Template Filter Syntax error

佐手、 提交于 2019-12-05 08:47:45

问题


I am trying to use django's built in 'default' filter using this code

{% load sekizai_tags static compress i18n %}
[...]
<title>{{ title|default:"nothing" }}</title>

But it gives me the following exception

django.template.base.TemplateSyntaxError: default requires 2 arguments, 1 provided

I am using the following settings for my Template Backend

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            str(APPS_DIR.path('templates')),
        ],
        'OPTIONS': {
            'debug': DEBUG,
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'allauth.account.context_processors.account',
                'allauth.socialaccount.context_processors.socialaccount',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'sekizai.context_processors.sekizai',
            ],
        },
    },
]

My editor marks the code as invalid, but i check like a thousand of times https://docs.djangoproject.com/en/1.8/ref/templates/builtins/

Where this is given as example:

{{ value|default:"nothing" }}

I also tried to change the name of title var, to make sure it is not a reserved keyword.


回答1:


Make sure you don't have a space after the colon.

This is correct:

{{ title|default:"nothing" }}

This throws an exception:

{{ title|default: "nothing" }}



回答2:


Try :

{{ title|default_if_none:"nothing" }}

default_if_none will display the given string if the variable is 'None'.

default will display the string if the variable evaluates to False, ie empty strings, empty lists etc

Also make sure you send title variable in your context , if not you must use default_if_none



来源:https://stackoverflow.com/questions/30662793/django-template-filter-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!