Given this custom filter that reverses a string, what will be the output of {{ 'hello'|reverse_string }} in a Django template?
from django import template register = template.Library() @register.filter def reverse_string(value): return value[::-1]
Think about what slicing with [::-1] does to a string.
The filter reverse_string returns the input string reversed. So 'hello' becomes 'olleh'.
Which of the following code snippets correctly registers a custom Django template filter named double that doubles a number?
Look for the correct decorator usage and import style.
Option A uses the correct import, creates a Library instance, and registers the filter with the decorator and name argument.
Consider this filter code:
from django import template
register = template.Library()
@register.filter
def add_prefix(value, prefix):
return prefix + valueUsing {{ 'world'|add_prefix:'Hello ' }} in a template causes a TemplateSyntaxError. Why?
Check how to pass arguments to filters in Django templates.
Custom filters can accept an argument, but the template syntax must use a colon to pass it, like {{ value|filter:arg }}. The code is correct, but the error is due to incorrect template usage or missing quotes.
Given these filters:
from django import template
register = template.Library()
@register.filter
def shout(value):
return value.upper() + '!!!'
@register.filter
def repeat(value, times=2):
return value * timesWhat is the output of {{ 'hi'|shout|repeat:3 }} in a Django template?
Remember the order filters are applied and how arguments are passed.
The string 'hi' is first converted to uppercase with '!!!' added by shout, resulting in 'HI!!!'. Then repeat multiplies this string 3 times, producing 'HI!!!HI!!!HI!!!'.
Choose the correct statement about Django custom template filters.
Think about how filters are registered and used in templates.
Filters must be registered with a Library instance and the tag library must be loaded in the template to use them. Filters do not modify context or require returning strings only.