60
67

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでmarkdownを扱う

Last updated at Posted at 2014-01-07

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 }}
60
67
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
60
67

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?