I need to implement a template tag that will return a string with a collection of items from an object.
I had created the following structure:
produtos/
templatetags/
__init__.py
produto_tags.py
produto_tags.py:
# -*- coding: utf-8 -*-
from django import template
from django.template import Node
from produto.models import Produto
from django.template.loader import render_to_string
register = template.Library()
@register.tag
def get_all_tags(parser, token):
args = token.split_contents()
return ProdutoTemplateNode(args[1])
class ProdutoTemplateNode(Node):
def __init__(self, produto):
self.produto = produto
def render(self, context):
list = []
produto = template.Variable(self.produto).resolve(context)
tags = produto.tags.all()
if tags:
for tag in tags:
list.append(tag.name)
return ", ".join(list)
else:
return u'Não existem tags para este produto'
Template:
{% load produto_tags %}
...
{% for produto in produtos %}
<li id="{{ produto.ordenacao }}" data-tags="{% get_all_tags produto %}">
...
</li>
{% endfor %}
</ul>
{% else %}
<p>Não existem produtos cadastrados no sistema</p>
{% endif %}
I am receiving this error:
TemplateSyntaxError at /concrete/nossos-sites.html
Invalid block tag: 'get_all_tags', expected 'empty' or 'endfor'
I read other threads where people said this error occurs if the Tag does not exist and it seems to be the case. I’ve been looking on the djangoproject.com documentation as well and I could not find any clue about what might be happening.
Thanks!
That was tricky, even though simple:
First, there was another ‘produto_tags.py’ in another folder elsewhere in the project:
So, at first I have moved all code from produtos/templatetags/ to common/templatetags/. But when I did it Django started whining about not finding the produtos_tags from produtos. Afterwards I got the code back to produtos/templatetags/ and renamed the file to tags_produtos.py, what had worked to show the easy part that is my wrong import below:
Wrong:
Correct: