实现Django自定义模板标记的问题

时间:2012-04-19 16:41:54

标签: django python-2.7

我需要实现一个模板标记,它将返回一个包含来自对象的项集合的字符串。

我创建了以下结构:

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'

模板:

{% 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 %} 

我收到此错误:

TemplateSyntaxError at /concrete/nossos-sites.html
Invalid block tag: 'get_all_tags', expected 'empty' or 'endfor'

我读了其他线程,人们说如果Tag不存在就会出现这个错误,而且似乎就是这种情况。我一直在查看djangoproject.com文档,我找不到任何关于可能发生的事情的线索。

谢谢!

4 个答案:

答案 0 :(得分:3)

模板标记文件需要位于应用内的templatetags目录中。

答案 1 :(得分:2)

首先关注丹尼尔和伊格纳西奥的建议。另外,奇怪的是你在模板顶部有{% load produto_tags %}但是出现了无效的块错误:如果produto_tags无法加载,则错误应该是'produto_tags不是有效标记'blahblah 。您可以再次查看您发布的代码和路径结构吗?

答案 2 :(得分:2)

这很棘手,即使很简单:

首先,项目中其他地方的另一个文件夹中还有另一个'produto_tags.py':

project/
    common/
        templatetags/
            produtos_tags.py
    produtos/
        templatetags/
            produtos_tags.py

所以,首先我将所有代码从produtos / templatetags /移动到common / templatetags /。但当我这样做时,Django开始抱怨没有从produtos找到produtos_tags。之后我将代码返回到produtos / templatetags /并将文件重命名为tags_produtos.py,这些内容有助于显示下面我输入错误的简单部分:

错:

from produto.models import Produto

正确:

from produtos.models import Produto

答案 3 :(得分:-1)

改为使用{{ produto | get_all_tags }}

{% ... %}语法仅对for

等块标记有效

希望有所帮助。