博客五部曲之二 - 高级博客


1241 浏览 5 years, 3 months

6 用django去渲染markdown

版权声明: 转载请注明出处 http://www.codingsoho.com/

前面我们讲的内容都是通过前端去渲染markdown,有的时候会有一些局限,尤其是内容截断时。从这一节我们会讲解如果通过后端django去渲染markdown

这会用到库django-markdown-deux [https://github.com/trentm/django-markdown-deux](https://github.com/trentm/django-markdown-deux)

安装django-markdown-deux库

pip install django-markdown-deux

在model里直接生成markdown结果

from markdown_deux import markdown

# Create your models here.
class Post(models.Model):
    def get_markdown(self):
        content = self.content
        return markdown(content)

修改post_list的markdown显示为{{object.get_markdown}},之前用于markdown显示的css class “content-markdown”可以去掉
但是显示的图片内容为代码格式,我们还是需要将他们转化为html内容
有两个方法可以完成这个转换,可以在前端通过filter {{object.get_markdown|safe}},也可以在后端通过mark_safe函数

from markdown_deux import markdown
from django.utils.safestring import mark_safe

# Create your models here.
class Post(models.Model):
    ...
    def get_markdown(self):
        content = self.content
        markdown_content = markdown(content)
        return mark_safe(markdown_content)

因为现在开始用django来实现markdown,所有前端不需要再通过JS来渲染,修改如下
在post_list.html里面,将markdown内容的显示改为object.get_markdown,去掉之前的content-markdown class,在它的父节点添加一个新class “post-detail-item”,这个会用于后面的图片处理

  <div class="caption post-detail-item">
    {% if object.draft %} <h3>Draft {% if object.publish > today %}Staff Only : Future Post{% endif %}</h3>{% endif %}
    <h3><a href="{{ object.get_absolute_url }}">{{object.title}}</a> <small>{{object.timestamp|timesince}}</small></h3>
    {% if object.user.get_full_name %}
    <p>Autho: {{object.user.get_full_name}}</p>
    {% endif %}
    {{object.get_markdown}}
    <p><a href="{{ object.get_absolute_url }}" class="btn btn-default" role="button">View</a></p>
  </div>

在post_detail.html完成类似修改

<div class="row">
    <div class="col-sm-12">
        <div class="post-detail-item">{{instance.get_markdown}}</div>
    </div>
</div>    

最后,在base.html里修改代码,用新的class去做元素选择器

<script type="text/javascript">
    $(document).ready(function(){
        $(".post-detail-item img").addClass('img-responsive');
    })
</script>