Allow for tables without header row

fixes #42
This commit is contained in:
AlexVonB
2021-05-16 19:02:00 +02:00
parent fc29483899
commit 7dac92e85e
2 changed files with 36 additions and 17 deletions

View File

@@ -279,14 +279,20 @@ class MarkdownConverter(object):
def convert_table(self, el, text, convert_as_inline):
rows = el.find_all('tr')
text_data = []
rendered_header = False
for row in rows:
headers = row.find_all('th')
columns = row.find_all('td')
if len(headers) > 0:
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)) + ' |')
rendered_header = True
elif len(columns) > 0:
if not rendered_header:
text_data.append('| ' + ' | '.join([''] * len(columns)) + ' |')
text_data.append('| ' + ' | '.join(['---'] * len(columns)) + ' |')
rendered_header = True
columns = [colm.text.strip() for colm in columns]
text_data.append('| ' + ' | '.join(columns) + ' |')
else:

View File

@@ -41,8 +41,7 @@ nested_ols = """
</ul>"""
table = re.sub(r'\s+', '', """
<table>
table = """<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
@@ -58,18 +57,16 @@ table = re.sub(r'\s+', '', """
<td>Jackson</td>
<td>94</td>
</tr>
</table>
""")
</table>"""
table_head_body = re.sub(r'\s+', '', """
<table>
table_head_body = """<table>
<thead>
<tr>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
</tr>
</thead>
<tbody>
<tr>
@@ -83,17 +80,15 @@ table_head_body = re.sub(r'\s+', '', """
<td>94</td>
</tr>
</tbody>
</table>
""")
</table>"""
table_missing_text = re.sub(r'\s+', '', """
<table>
table_missing_text = """<table>
<thead>
<tr>
<tr>
<th></th>
<th>Lastname</th>
<th>Age</th>
</tr>
</tr>
</thead>
<tbody>
<tr>
@@ -107,8 +102,25 @@ table_missing_text = re.sub(r'\s+', '', """
<td>94</td>
</tr>
</tbody>
</table>
""")
</table>"""
table_missing_head = """<table>
<tr>
<td>Firstname</td>
<td>Lastname</td>
<td>Age</td>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>"""
def test_chomp():
@@ -325,6 +337,7 @@ def test_table():
assert md(table) == '| 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 |'
def test_strong_em_symbol():