Django,自定义标签......怎么样?

时间:2009-09-20 04:20:46

标签: django django-templates django-custom-tags

我想制作一个django自定义标签,以显示用户正在阅读文章的类别中的10个条目标题。我怎样才能做到这一点?我需要从实际条目中传递类别。

3 个答案:

答案 0 :(得分:8)

执行此操作的最佳方法是使用包含标记。这是一个标记,用于呈现呈现10个相关文章的模板片段。

您只需将当前文章传入标记,然后返回模板片段的上下文 - 即相关文章。

@register.inclusion_tag('related_articles.html')
def related_articles(article, count):
    category = article.category
    articles = category.article_set.exclude(id=article.id)[:count]
    return {'articles': articles}

您需要在您的模板目录中输出related_articles.html文件,该文件会输出文章。然后,要从主模板中调用它,您只需执行

{% related_articles article 10 %}

其中article是文章对象的名称。

答案 1 :(得分:2)

为什么要自定义标签?将一个方法添加到文章模型并从模板中调用它可能更好,更清晰。根据您的型号,该方法几乎是微不足道的。

答案 2 :(得分:1)

点击此处查看自定义标记:

http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags

您需要将相关的类别对象传递给模板上下文。