简体   繁体   中英

How do I add Attributes to Tables in Python-Markdown

Following this documentation:

http://pythonhosted.org/Markdown/extensions/attr_list.html

This works:

### This makes a title {: .with-some-class }

I need to add classes to tables, but it's not working:

| Title | blabla 
-----------------
| foo   | bar {: .with-some-class }

Any ideas?

You've discovered an incompatibility between the attr_list and tables extensions. <td> is a block-level element, so by default, attr_list looks for the attribute list on the next line, not inline. I think there is a good case for an exception for cell elements (as there currently are for header elements), because there is no way to have multi-line cells with the tables extension.

To decide which solution to implement, you'll have to weigh the pain of switching to a new table format with that of switching to a development version of python-markdown.

Block Level Solution: use grid_tables rather than tables (recommended)

Grab the third-party Grid Tables extension , which supports multi-line cells, and put your attribute list it's own line like so:

+-------+----------+-------------------------------+
| Title            | blabla                        |
+=======+==========+===============================+
| foo   | bar                                      |
|       | {: class="foo bar" title="Some title!" } |
+-------+------------------------------------------+

Output:

<table>
<thead>
<tr>
<th colspan="2" rowspan="1">
<p>Title</p>
</th>
<th colspan="1" rowspan="1">
<p>blabla</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="1" rowspan="1">
<p>foo
</p>
</td>
<td colspan="2" rowspan="1">
<p class="foo bar" title="Some title!">bar</p>
</td>
</tr>
</tbody>
</table>

Inline Solution: modify attr_list to be compatible with tables

attr_list can support inline attribute lists on cell elements by adding the following lines to attr_list.py:

if not m and elem.tag == 'td':
    m = re.search(self.BASE_RE, elem.text)

Unfortunately, both of these extensions are part of extra , which is built into python-markdown. They rely on internal modules, so making your own extension (compatible with the current pip package) isn't realistic. If you want to implement this solution now, you can install my fork .

Note: you cannot leave any space between the cell content and attribute list (as you did in your question).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM