|
| 1 | +"""A custom Sphinx HTML Translator for Bootstrap layout |
| 2 | +""" |
| 3 | +import sys |
| 4 | +import re |
| 5 | + |
| 6 | +from docutils import nodes |
| 7 | + |
| 8 | +from sphinx.locale import admonitionlabels, _ |
| 9 | +from sphinx.writers.html5 import HTML5Translator |
| 10 | + |
| 11 | + |
| 12 | +# Mapping of admonition classes to Bootstrap contextual classes |
| 13 | +alert_classes = { |
| 14 | + "attention": "primary", |
| 15 | + "caution": "warning", |
| 16 | + "danger": "danger", |
| 17 | + "error": "danger", |
| 18 | + "hint": "info", |
| 19 | + "important": "primary", |
| 20 | + "note": "info", |
| 21 | + "seealso": "info", |
| 22 | + "tip": "primary", |
| 23 | + "warning": "warning", |
| 24 | + "todo": "info", |
| 25 | + "example": "info", |
| 26 | +} |
| 27 | + |
| 28 | + |
| 29 | +class BootstrapHTML5Translator(HTML5Translator): |
| 30 | + """Custom HTML Translator for a Bootstrap-ified Sphinx layout |
| 31 | +
|
| 32 | + This is a specialization of the HTML5 Translator of sphinx. |
| 33 | + Only a couple of functions have been overridden to produce valid HTML to be |
| 34 | + directly styled with Bootstrap. |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, *args, **kwds): |
| 38 | + super().__init__(*args, **kwds) |
| 39 | + self.settings.table_style = "table" |
| 40 | + |
| 41 | + def visit_admonition(self, node, name=""): |
| 42 | + # type: (nodes.Element, str) -> None |
| 43 | + # copy of sphinx source to add alert classes |
| 44 | + classes = ["alert"] |
| 45 | + if name: |
| 46 | + classes.append("alert-{0}".format(alert_classes[name])) |
| 47 | + self.body.append(self.starttag(node, "div", CLASS=" ".join(classes))) |
| 48 | + if name: |
| 49 | + node.insert(0, nodes.title(name, admonitionlabels[name])) |
| 50 | + |
| 51 | + def visit_table(self, node): |
| 52 | + # type: (nodes.Element) -> None |
| 53 | + # copy of sphinx source to *not* add 'docutils' and 'align-default' classes |
| 54 | + # but add 'table' class |
| 55 | + self.generate_targets_for_table(node) |
| 56 | + |
| 57 | + self._table_row_index = 0 |
| 58 | + |
| 59 | + classes = [cls.strip(" \t\n") for cls in self.settings.table_style.split(",")] |
| 60 | + # classes.insert(0, "docutils") # compat |
| 61 | + # if 'align' in node: |
| 62 | + # classes.append('align-%s' % node['align']) |
| 63 | + tag = self.starttag(node, "table", CLASS=" ".join(classes)) |
| 64 | + self.body.append(tag) |
0 commit comments