How to add rel attribute to docutils sphinx reference in HTML output?

我与影子孤独终老i 提交于 2019-12-10 19:44:34

问题


I have a simple extension for the Sphinx documentation utility (my version in use isSphinx-1.1.3-py2.6). Very much like this excellent example by Doug Hellmann. How can I add a rel='bar' attribute to the final HTML for the tag?

There seems to be a few ways to do this, but I couldn't find a simple one. Advise and tips are appreciated.

The reference nodes are created in this fashion:

node = nodes.reference(rawtext, utils.unescape(text),
            internal=False,
            refuri=ref,
            classes=['foocss'],
            rel='bar',
            **options)

However, the rel='bar' attribute gets stripped out from the final HTML markup. Hunting through the source got me to sphinx/writers/html.py and the HTMLTranslator class. Here is part of the visit_reference method:

# overwritten
def visit_reference(self, node):
    atts = {'class': 'reference'}

    <snip>

    if 'reftitle' in node:
        atts['title'] = node['reftitle']
    self.body.append(self.starttag(node, 'a', '', **atts))

Additional attributes are not handled. Maybe they could be replaced in others parts. I couldn't find anything useful in that respect.

So, I could:

  • create a custom node which reimplements all the functionality of the reference node. A fair bit of work for a small addition.
  • Overwrite the *visit_reference* method in sphinx/writers/html.py. Quicker, but bad in terms of future Sphinx updates.
  • Add the rel attribute with jQuery to the link tag after the fact. Well, not pretty either.

I'm sure I'm missing the obvious and elegant solution.

Thanks!


回答1:


I managed to do this with download_reference. Using app.add_node I override the visit_... method:

import posixpath
from sphinx.writers.html import HTMLTranslator
from sphinx.addnodes import download_reference

def visit_download_reference(self, node):
    if node.hasattr('filename'):
        self.body.append(
            '<a class="reference download internal" href="%s" %s>' %
            (posixpath.join(self.builder.dlpath, node['filename']), 'rel="%s"' % node['rel'] if node.get('rel', None) else ''))
        self.context.append('</a>')
    else:
        self.context.append('')

def setup(app):
    app.add_node(download_reference, html=(visit_download_reference, HTMLTranslator.depart_download_reference))

full extension is here



来源:https://stackoverflow.com/questions/13168702/how-to-add-rel-attribute-to-docutils-sphinx-reference-in-html-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!