djiango自定義標籤與過濾器
阿新 • • 發佈:2018-12-10
from django import template #關鍵程式碼 register = template.Library() #關鍵程式碼 from django.db.models import Count from django.utils.safestring import mark_safe from article.models import ArticlePost import markdown #1、返回單個數字 # {% load article_tags %} 必須要有 @register.simple_tag def total_articles(): return ArticlePost.objects.count() # {% total_articles %} @register.simple_tag def author_total_articles(user): return user.article.count() # {% author_total_articles user %} #2、返回html程式碼 @register.inclusion_tag('article/list/lastest_articles.html') def latest_articles(n=5): lastest_articles = ArticlePost.objects.order_by("-created")[:n] return {"latest_articles":lastest_articles} # {% latest_articles 4 %} #3、返回物件陣列 @register.assignment_tag def most_commented_articles(n=3): return ArticlePost.objects.annotate(total_counts = Count('comments')).order_by('-total_comments')[:n] # {% most_commented_articles as most_comments %} # {% for comment_article in most_comments %} #這個是必須的,定義變數。 # {% endfor %} #4,自定義過濾器 @register.filter(name='markdown') #重新命名,方便前端呼叫,遵從使用習慣 def markdown_filter(text): #不能是markdown,與import markdown衝突 return mark_safe(markdown.markdown(text)) # {% article.boyd | markdown %}