Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of links from python with a sphinx directive

I have an rst file that contains:

..include:: other_file.rst

and other_file.rst contains something like:

* `Text Item 1 <https://link/to/somewhere>`__
* `Text Item 2 <https://link/to/somewhere_else>`__

Right now I pre-generate other_file.rst and then run sphinx-build to generate the final HTML.

What I'd like to do is switch this up so I have a custom Sphinx directive that generates the list for me.

something like:

from docutils import nodes
from docutils.parsers.rst import Directive
class MyDirective(Directive):
    def run(self):
        my_nodes = node.bullet_list(bullet='*')
        for text, ref in [('Text Item 1', 'https://link/to/somewhere'),
                          ('Text Item 2', 'https://link/to/somewhere_else')]:
            item = nodes.list_item()
            # Magic happens
            my_nodes.append(item)
        return [my_nodes]

If I replace # Magic happens with item += nodes.paragraph(text) I get a list of the items but when I try to use nodes.reference(...) I get a list of empty bullets.

I'm clearly doing something close to right but missing something simple.

like image 361
tonyb Avatar asked Nov 17 '22 15:11

tonyb


1 Answers

Reference should be placed inside some container like paragraph and have inner node to be represented somehow

    def run(self):
        my_nodes = nodes.bullet_list(bullet='*')
        for text, ref in [('Text Item 1', 'https://link/to/somewhere'),
                          ('Text Item 2', 'https://link/to/somewhere_else')]:
            item = nodes.list_item()
            # Magic happens
            para = nodes.paragraph(text=text)
            refnode = nodes.reference('', '', internal=False, refuri=ref)
            innernode = nodes.emphasis("link", "link")
            refnode.append(innernode)
            para += refnode
            item += para
            my_nodes.append(item)
        return [my_nodes]

This code produces list with text fields and links

generation result

like image 164
vsh Avatar answered Feb 01 '23 02:02

vsh