Python-Markdown 插件html
安裝python
pip install markdown
modelsdjango
from django.utils import timezone from django.db import models from django.contrib.auth.models import User # 導入django自帶的用戶模型 from django.utils.html import mark_safe # 將字符串標記爲安全進行輸出 from markdown import markdown # 導入 markdown 插件,將markdown格式轉化爲html class Comment(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) comment_text = models.TextField(max_length=2000) author = models.ForeignKey(User, default=1, on_delete=models.CASCADE) picture = models.FileField(blank=True, null=True) # 添加文件類型字段,並默認爲空 pub_date = models.DateTimeField(auto_now_add=True) def get_comment_text_md(self): """將markdown格式轉化爲html""" return mark_safe(markdown(self.comment_text)) def __str__(self): return self.comment_text
templates:安全
{% for comment in topic.comment_set.all %} {{ comment.get_comment_text_md }} {% endfor %}
此時,模板中經過 get_comment_text_md
將 conment_text
中的 markdown 文本轉化爲 html 在前臺頁面顯示。markdown
模板中引用.net
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css"> ... <script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script> <script> var simplemde = new SimpleMDE(); // 會尋找當前頁面第一個textarea進行渲染 </script>
此時該插件就會在頁面中尋找第一個textarea,並進行樣式渲染。效果以下。
插件