Django 中使用 MarkDown 插件


Django 使用 markdown 插件

Python-Markdown 插件

安裝

pip install markdown

1 將 markdown 轉化為 html

models

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_mdconment_text 中的 markdown 文本轉化為 html 在前台頁面顯示。

2 使用 markdown 編輯框

模板中引用

<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,並進行樣式渲染。效果如下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM