问题
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