I am trying to use a custom template tag and it gives me this error when I am trying to get a rendered page:
Invalid block tag on line 29: 'get_message_print_tag', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I am trying to get a simple title for my flash messages based on {{message.tags}}
and make it bold in my template. Where am I making a mistake?
apptags.py:
from django import template
register = template.Library()
def get_message_print_tag(value):
'''return a string for a message tag depending on the
message tag that can be displayed bold on the flash message'''
if 'danger' in value.lower():
return 'ERROR'
elif 'success' in value.lower():
return 'SUCCESS'
else:
return 'NOTE'
html:
{% load apptags %}
<div class="bootstrap-iso">
{% if messages %}
<div class="messages ">
{% for message in messages %}
<div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error: {% endif %}
<strong> {% get_message_print_tag {{message.tags}} %} </strong>
{{ message }}
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
</div>
{% endfor %}
</div>
{% endif %}
</div>
from Django documentation: Simple Tags
To ease the creation of tags that take a number of arguments – strings or template variables – and return a result after doing some processing based solely on the input arguments and some external information, Django provides a helper function, simple_tag
. This function, which is a method of django.template.Library
, takes a function that accepts any number of arguments, wraps it in a render function and the other necessary bits mentioned above and registers it with the template system.
So the problem was only one line which should be above the definition of the tag:
from django import template
register = template.Library()
@register.simple_tag
def get_message_print_tag(value):
'''return a string for a message tag depending on the
message tag that can be displayed bold on the flash message'''
if 'danger' in value.lower():
return 'ERROR'
elif 'success' in value.lower():
return 'SUCCESS'
else:
return 'NOTE'