Django, custom tag… how?

青春壹個敷衍的年華 提交于 2019-12-23 03:23:07

问题


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.


回答1:


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.




回答2:


Why a custom tag? It's probably better, cleaner, to add a method to the article model, and call that from the template. Depending on your model, the method would be practically trivial.




回答3:


Check here for making custom tags:

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

You would need to pass the relevant category object to the template context.



来源:https://stackoverflow.com/questions/1450289/django-custom-tag-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!