Skip to content

Instantly share code, notes, and snippets.

@shimizukawa
Last active August 29, 2015 14:08
Show Gist options
  • Save shimizukawa/37e26f6353327dad3f9d to your computer and use it in GitHub Desktop.
Save shimizukawa/37e26f6353327dad3f9d to your computer and use it in GitHub Desktop.
link2rst : Sphinx linkto context function for template of HTML builder. (CC BY)
# -*- coding: utf-8 -*-
templates_path = ['_templates']
master_doc = 'index'
html_sidebars = {'**': ['link2rst.html']}
### if you want to use intersphinx
extensions = ['sphinx.ext.intersphinx']
intersphinx_mapping = {'sphinx': ('http://sphinx-doc.org', None)}
### end
def _linkto_local(app, pagename, label):
docname, labelid = app.env.domains['std'].data['anonlabels'].get(label, ('', ''))
if not labelid:
return None
if docname == pagename:
url = '#' + labelid
else:
url = app.builder.get_relative_uri(pagename, docname) + '#' + labelid
return url
def _linkto_intersphinx(app, label):
from sphinx.ext.intersphinx import missing_reference
from sphinx.addnodes import pending_xref
from docutils.nodes import Text
dummy_node = Text(label)
refnode = pending_xref(label, reftype='ref', refdomain='std', reftarget=label, refwarn=True)
refnode += dummy_node
newnode = missing_reference(app, app.env, refnode, dummy_node)
if newnode is None:
return None
return newnode.get('refuri')
def update_page_context(app, pagename, templatename, context, doctree):
def linkto(label):
url = _linkto_local(app, pagename, label)
if not url and hasattr(app.config, 'intersphinx_mapping'):
url = _linkto_intersphinx(app, label)
return url
context['linkto'] = linkto
def setup(app):
app.connect('html-page-context', update_page_context)
.. store this file as 'index.rst'
link2rst
=========
.. _some-label:
This is a Labeled section
==========================
Hello
{# store this file in the _templates directory #}
<ul>
<li><a href="{{ linkto('some-label') }}">Link to Some Label</a></li>
<li><a href="{{ linkto('sphinx:build-config') }}">Link to Sphinx build config</a></li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment