Skip to content

Commit c706280

Browse files
author
yangxg
committed
Merge branch 'Step24_extract-content-automatically-using-markdown' into demo
2 parents 089927d + 304d6bd commit c706280

File tree

2 files changed

+12
-23
lines changed

2 files changed

+12
-23
lines changed

blog/views.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import markdown
22

3+
from markdown.extensions.toc import TocExtension
4+
35
from django.shortcuts import render, get_object_or_404
46
from django.views.generic import ListView, DetailView
7+
from django.utils.text import slugify
8+
59
from comments.forms import CommentForm
610
from .models import Post, Category, Tag
711

@@ -227,12 +231,13 @@ def get(self, request, *args, **kwargs):
227231
def get_object(self, queryset=None):
228232
# 覆写 get_object 方法的目的是因为需要对 post 的 body 值进行渲染
229233
post = super(PostDetailView, self).get_object(queryset=None)
230-
post.body = markdown.markdown(post.body,
231-
extensions=[
232-
'markdown.extensions.extra',
233-
'markdown.extensions.codehilite',
234-
'markdown.extensions.toc',
235-
])
234+
md = markdown.Markdown(extensions=[
235+
'markdown.extensions.extra',
236+
'markdown.extensions.codehilite',
237+
TocExtension(slugify=slugify),
238+
])
239+
post.body = md.convert(post.body)
240+
post.toc = md.toc
236241
return post
237242

238243
def get_context_data(self, **kwargs):

templates/blog/detail.html

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -78,22 +78,6 @@ <h3>评论列表,共 <span>{{ post.comment_set.count }}</span> 条评论</h3>
7878
{% block toc %}
7979
<div class="widget widget-content">
8080
<h3 class="widget-title">文章目录</h3>
81-
<ul>
82-
<li>
83-
<a href="#">教程特点</a>
84-
</li>
85-
<li>
86-
<a href="#">谁适合这个教程</a>
87-
</li>
88-
<li>
89-
<a href="#">在线预览</a>
90-
</li>
91-
<li>
92-
<a href="#">资源列表</a>
93-
</li>
94-
<li>
95-
<a href="#">获取帮助</a>
96-
</li>
97-
</ul>
81+
{{ post.toc|safe }}
9882
</div>
9983
{% endblock toc %}

0 commit comments

Comments
 (0)