Leonardo D'Amato
Leonardo D'Amato

Reputation: 23

Django - Custom tag not working

I want to pass a model to template base.html.

I read about custom tags, and tried to execute this. It is not throwing any error, but is not working too.

My code:

base.html:

{% load staticfiles %}
{% load tags %}

<!DOCTYPE html>
<html>
        <head>
        </head>
        <body>
         <ul class="dropdown-menu" role="menu">
            {% for league in get_my_leagues %}
            <li> ddddd {{ league.league_name }}</li>
            {% endfor %}
         </ul>

        {% block content %}
        {% endblock %}
    </body>
</html>

Now, tags.py:

from django.template import Library
from login.models import League

register = Library()

@register.inclusion_tag('base.html')
def get_my_leagues():
    return League.objects.all()

register.tag('get_my_leagues', get_my_leagues)

Upvotes: 0

Views: 891

Answers (2)

Leonardo D&#39;Amato
Leonardo D&#39;Amato

Reputation: 23

guys.

I'm here just to tell that i found a solution for my problem. I'm using Context Processors to do this job.

Thank you all for answers!

Upvotes: 0

koniiiik
koniiiik

Reputation: 4392

When you use {% for x in y %}, this expects that y is a context variable in your template, not a template tag.

What an inclusion tag does is that it renders a template (the one you pass as argument to the inclusion_tag decorator), and inserts the result where the inclusion tag is used.

You probably want to register get_my_leagues as a simple tag instead (or an assignment tag, if you're using Django older than 1.9), and use it like this:

{% get_my_leagues as my_leagues %}
{% for league in my_leagues %}
    ...
{% endfor %}

Upvotes: 2

Related Questions