Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
68
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

pythonでmarkdownを扱う

PythonでMarkdownを扱う

  • pypi:Markdown
    これをダウンロードしてセットアップ。
md_test.py
import markdown

md = markdown.Markdown()

sample_makedown = '''
An h1 header
============

Paragraphs are separated by a blank line.

2nd paragraph. *Italic*, **bold**, `monospace`. Itemized lists
look like:

  * this one
  * that one
  * the other one
'''

# makedown -> html
print md.convert(sample_makedown)

print結果は以下です。

出力結果
<h1>An h1 header</h1>
<p>Paragraphs are separated by a blank line.</p>
<p>2nd paragraph. <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>. Itemized lists
look like:</p>
<ul>
<li>this one</li>
<li>that one</li>
<li>the other one</li>
</ul>

こんなかんじでconvertしてあげるだけで、
MarkdownのテキストをHTMLに変換してくれます。

とても使いやすいですね。

ファイルに書き込みとかも対応しています。

Djangoで使う

Djangoで使う場合は次のようなフィルタを自作してあげます

myfilter.py
import markdown
#キャッシュするためここで宣言、初期化しとく
md = markdown.Markdown()

@register.filter
@stringfilter
def mark2html(value):
    return md.convert(value)
template.html
{% load myfilter %}

{{ markdown_text|mark2html }}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
68
Help us understand the problem. What are the problem?