Django custom template tag is not being executed

JuanXarg

I have a custom template tag that looks like this:

{% extends 'forms/base_template.html' %}

{% load mytags %}

{% mytag user 'hello' as greeting %}

{% block additional_info %}
{{ greeting }}
{% endblock %}

My tags are something like this:

from django import template

register = template.Library()


@register.assignment_tag(takes_context=False)
def mytag(user, what_to_say):
    return "{what_to_say} {user}".format(
        what_to_say=what_to_say,
        user=user.name
    )

But the code is never executed and the greeting variable is empty.

Any ideas what may be going on?

JuanXarg

OK, I found out just before I published. Thought to share just in case someone else gets bitten by this.

Apparently the tags need to be included within the same block they are being used. Couldn't find any relevant docs. So if the template looks like this:

{% extends 'forms/base_template.html' %}

{% load mytags %}

{% block additional_info %}
{% mytag user 'hello' as greeting %}
{{ greeting }}
{% endblock %}

it will work as expected. Nothe the {% mytag %} call is now included within the block.

UPDATE: Found some relevant info (kind of hidden) in the docs.

Variable scope in context

Any variable set in the context will only be available in the same block of the template in which it was assigned. This behavior is intentional; it provides a scope for variables so that they don’t conflict with context in other blocks.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related