Created
September 22, 2014 19:06
-
-
Save tpdn/e77ca40dface1be32ba1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pythonのmarkdownのtableをbootstrap対応にしてみる | |
#例: | |
#table = etree.SubElement(parent, 'table', {'class':'table'}) | |
#class='table'表記はclassが予約語なのでアウト | |
import markdown.extensions.tables as t | |
class TableProcessor(t.TableProcessor): | |
cssclass='table table-striped table-bordered' | |
def run(self, parent, blocks): | |
from markdown.util import etree | |
""" Parse a table block and build table. """ | |
block = blocks.pop(0).split('\n') | |
header = block[0].strip() | |
seperator = block[1].strip() | |
rows = block[2:] | |
# Get format type (bordered by pipes or not) | |
border = False | |
if header.startswith('|'): | |
border = True | |
# Get alignment of columns | |
align = [] | |
for c in self._split_row(seperator, border): | |
if c.startswith(':') and c.endswith(':'): | |
align.append('center') | |
elif c.startswith(':'): | |
align.append('left') | |
elif c.endswith(':'): | |
align.append('right') | |
else: | |
align.append(None) | |
# Build table | |
table = etree.SubElement(parent, 'table', {'class':cssclass}) | |
thead = etree.SubElement(table, 'thead') | |
self._build_row(header, thead, align, border) | |
tbody = etree.SubElement(table, 'tbody') | |
for row in rows: | |
self._build_row(row.strip(), tbody, align, border) | |
class TableExtension(t.TableExtension): | |
def extendMarkdown(self, md, md_globals): | |
md.parser.blockprocessors.add('table', TableProcessor(md.parser), '<hashheader') | |
md = markdown.Markdown(safe_mode=True, extensions=['del_ins', 'fenced_code', TableExtension()]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment