Search code examples
restructuredtextrst2html.py

In the HTML output generated by rst2html, sections at all levels are all with class "section", can I config it?


In the HTML output generated by rst2html, sections at all levels are all with class "section". Can I config it?

Thus, if I want apply my own CSS to the HTML output, I just can not use different styles for top-level section and sub-section, because they have the same class name?

How to solve this problem if I want to apply different styles to sections at different level?


Solution

  • I have solved this problem by writing my own rst writer class Inheriting docutils.writers.html4css1.Writer, and in its constructor, assign it a instance of class HTMLTranslator Inheriting docutils.writers.html4css1.HTMLTranslator to its translator_class attribute.

    Specifically, in my HTMLTranslator class, the method visit_section is overridden::

    def visit_section(self, node):
        self.section_level += 1
        self.body.append(
            self.starttag(node, 'div', CLASS='section section%d' % self.section_level))
    

    Thus, section at level 2 will get a class section section2.