Created
May 15, 2011 20:30
-
-
Save tkf/973504 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/python | |
| """ | |
| A toy example of table generation in docutils | |
| Most of the code is coming from `ListTable.build_table_from_list` in | |
| `docutils.parsers.rst.directives.tables`. | |
| Usage:: | |
| python my_table_2x2.py > sample.html | |
| or:: | |
| python -c "from my_table_2x2 import sample; print sample()['body']" | |
| """ | |
| from docutils.parsers.rst import Directive | |
| from docutils import nodes | |
| def gene_paragraph(rawtext): | |
| paragraph = nodes.paragraph() | |
| paragraph += nodes.Text(rawtext) | |
| return paragraph | |
| def gene_entry(paragraph): | |
| entry = nodes.entry() | |
| entry += paragraph | |
| return entry | |
| class MyTable2x2(Directive): | |
| def run(self): | |
| table = nodes.table() | |
| tgroup = nodes.tgroup(cols=2) | |
| tbody = nodes.tbody() | |
| colspec0 = nodes.colspec(colwidth=50) | |
| colspec1 = nodes.colspec(colwidth=50) | |
| rows = [nodes.row() for i in range(2)] | |
| table += tgroup | |
| tgroup += colspec0 | |
| tgroup += colspec1 | |
| tgroup += tbody | |
| tbody.extend(rows) | |
| entries = dict( | |
| ((i ,j), gene_entry(gene_paragraph("this is cell %d%d" % (i ,j)))) | |
| for i in range(2) for j in range(2)) | |
| for i in range(2): | |
| for j in range(2): | |
| rows[i] += entries[i,j] | |
| table['classes'] += ['my-table'] | |
| return [table] | |
| def register_my_table_2x2(): | |
| from docutils.parsers.rst import directives | |
| directives.register_directive("my-table-2x2", MyTable2x2) | |
| def sample(writer_name="html"): | |
| """ | |
| Sample usage of `my-table-2x2` directive | |
| """ | |
| register_my_table_2x2() | |
| from docutils.core import publish_parts | |
| return publish_parts(".. my-table-2x2::", writer_name=writer_name) | |
| if __name__ == '__main__': | |
| print sample()["whole"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment