Django,自定义标签...怎么样? [英] Django, custom tag... how?

查看:96
本文介绍了Django,自定义标签...怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个django自定义标签,从用户阅读文章的类别中显示10个条目标题。我该怎么做?我需要从实际条目中传递类别。

解决方案

最好的方式是使用包含标签。这是一个标签,用于呈现一个模板片段,呈现10个相关文章。



您只需将当前文章传递到标签中,并返回模板片段的上下文,即相关文章。

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

您需要在templates目录中输入一个related_articles.html文件才能输出文章。然后,从主模板中调用它,您只需执行

  {%related_articles article 10%} 

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

I would like to make a django custom tag to display 10 entry titles from the category where the user is reading an article. How can I do this? I need to pass the category from the actual entry.

解决方案

The best way to do this would be with an inclusion tag. This is a tag that renders a template fragment which renders the 10 related articles.

You just pass in the current article into the tag, and return the context for the template fragment - ie the related articles.

@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}

You'll need a related_articles.html file in your templates directory which outputs the articles. Then, to call it from your main template, you would just do

{% related_articles article 10 %}

where article is the name of the article object.

这篇关于Django,自定义标签...怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆