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

Asi*_*nox 1 django django-templates django-custom-tags

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

Dan*_*man 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}
Run Code Online (Sandbox Code Playgroud)

您需要在您的模板目录中输出related_articles.html文件,该文件将输出文章.然后,要从主模板中调用它,您就可以了

{% related_articles article 10 %}
Run Code Online (Sandbox Code Playgroud)

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

  • http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/ James Bannet描述了一种技术,如何制作更通用的标签.即你可以使用一个template_tag作为模型"新闻","文章","事件"...它并不想要你描述,但值得一读. (2认同)