Django自定義markdown過濾器

2021-09-06 06:53:39 字數 2054 閱讀 7782

一 安裝第三方庫markdown

(venv) e:\django\mysite>pip install markdown
二 在mysite/article/templatetags/article_tags.py定義markdown過濾器

# template包含了很多與模板有關的類和方法

from django import template

from django.db.models import count

from django.utils.safestring import mark_safe

import markdown

# library是template類的乙個方法

# register包含了******_tag方法

# 它將用於自定義標籤

register = template.library()

from article.models import articlepost

# 表明下面的**是自定義的******_tag

@register.******_tag

def total_articles():

# 返回文章物件的查詢結果

return articlepost.objects.count()

@register.******_tag

def author_total_articles(user):

# 返回某個作者的文章總數

return user.article.count()

# 用裝飾器宣告自定義標籤,通過引數確定所渲染的模板檔案

@register.inclusion_tag('article/list/latest_articles.html')

# 在具體使用標籤時,會通過n傳參

def latest_articles(n=5):

# 按照發布時間倒排序,排序個數由n來決定

latest_articles = articlepost.objects.order_by("-created")[:n]

return

# 用裝飾器來宣告自定義的assignment_tag型別的標籤函式

@register.assignment_tag

def most_commented_articles(n=3):

# 給每一篇文章標註total_comments屬性

return articlepost.objects.annotate(total_comments=count('comments')).order_by("-total_comments")[:n]

# 重命令markdown_filter為markdown

@register.filter(name='markdown')

# 如果函式名為markdown,會和引入的markdown衝突,函式體會報錯

def markdown_filter(text):

# mark_safe返回safe string,可以區分html標籤中的符號和非html字元,例如「

return mark_safe(markdown.markdown(text))

三 編輯mysite/templates/article/list/article_detail.html,替換成markdown過濾器形式

}}

}like}

}view}

}-->

}

like

unlike

點讚本文的讀者

}還沒有人對此文章表態

}說:

}

}

四 測試

Django 自定義標籤

模版是乙個用django模版語言標記過的python字串。模版可以包含模版標籤和變數。模版標籤是在乙個模版裡起作用的標記。比如,乙個模版標籤可以產生控制結構的內容 if或者for 可以獲取資料庫內容或者訪問其它模版標籤。乙個標籤塊被包圍 變數標籤被 包圍 context是乙個傳遞給模版的key va...

Django自定義函式

templates 母版.html 引入 extends include 自定義函式 simpla tag 2.任意python檔案 a.from django import template from django.utils.safestring import mark safe registe...

django自定義Color Picker控制項

django提供了豐富的部件,以滿足我們對各種html控制項的需求。並且如果有特別的要求,我們還可以很容易的編寫自己的控制項,本文主要內容是自定義乙個顏色選擇器的控制項,該控制項是在input的基礎上,實現顏色的選擇和展示。如果你不知道如何實現自定義django的form控制項的話,可以檢視djan...