allow tables with headers in first (or any) column
This commit is contained in:
@@ -281,20 +281,19 @@ class MarkdownConverter(object):
|
||||
text_data = []
|
||||
rendered_header = False
|
||||
for row in rows:
|
||||
headers = row.find_all('th')
|
||||
columns = row.find_all('td')
|
||||
if not rendered_header and len(headers) > 0:
|
||||
headers = [head.text.strip() for head in headers]
|
||||
text_data.append('| ' + ' | '.join(headers) + ' |')
|
||||
text_data.append('| ' + ' | '.join(['---'] * len(headers)) + ' |')
|
||||
cells = row.find_all(['td', 'th'])
|
||||
is_headrow = all([cell.name == 'th' for cell in cells])
|
||||
texts = [cell.text.strip() for cell in cells]
|
||||
if not rendered_header and is_headrow:
|
||||
text_data.append('| ' + ' | '.join(texts) + ' |')
|
||||
text_data.append('| ' + ' | '.join(['---'] * len(cells)) + ' |')
|
||||
rendered_header = True
|
||||
elif len(columns) > 0:
|
||||
elif len(cells) > 0:
|
||||
if not rendered_header:
|
||||
text_data.append('| ' + ' | '.join([''] * len(columns)) + ' |')
|
||||
text_data.append('| ' + ' | '.join(['---'] * len(columns)) + ' |')
|
||||
text_data.append('| ' + ' | '.join([''] * len(cells)) + ' |')
|
||||
text_data.append('| ' + ' | '.join(['---'] * len(cells)) + ' |')
|
||||
rendered_header = True
|
||||
columns = [colm.text.strip() for colm in columns]
|
||||
text_data.append('| ' + ' | '.join(columns) + ' |')
|
||||
text_data.append('| ' + ' | '.join(texts) + ' |')
|
||||
else:
|
||||
continue
|
||||
return '\n'.join(text_data)
|
||||
|
||||
@@ -60,6 +60,25 @@ table = """<table>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_with_header_column = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Jill</th>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Eve</th>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_head_body = """<table>
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -335,6 +354,7 @@ def test_div():
|
||||
|
||||
def test_table():
|
||||
assert md(table) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table_with_header_column) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table_head_body) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table_missing_text) == '| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table_missing_head) == '| | | |\n| --- | --- | --- |\n| Firstname | Lastname | Age |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
|
||||
|
||||
Reference in New Issue
Block a user