Search code examples
pythonrestructuredtext

Custom directive for restuctured text?


I'm trying to use docutils's rst2html.py to convert rst document to html.

A external hyper link created with

`How to create Product <Django.url('reservation:manual:product:index')>`_

is converted to

<a class="reference external" href="Django.url('reservation:manual:product:index')">How to create Product</a>

I'd like to modify rst2html.py (or related files) so that I can generate the following instead.

<Link
to={Django.url('reservation:manual:product:index')}
>
</Link>

I don't need to use the embedded URIs format to express a link.

It seems I can create a custom directive to specify a parsing/generating rule.

But with my short knowledge of RST and its parsers, I'm not sure if I can embed a link for a word phrase in a sentence with directives.


Solution

  • I would simply write a post-processor. Assuming that Django URLs won't have internal markup or escapable characters like & and ", a simple regex will do here (despite the general cursedness for tasks even slightly more complex), like:

    import re
    s = ('head <a class="reference external" href="'
         "Django.url('reservation:manual:product:index')"
         '">How to create Product</a> tail')
    r = re.sub(r'<a class=".*?" href="(Django[.]url[(].*?[)])">.*?</a>', 
               r'<Link to={\1}></Link>', s)
    print(r)
    

    Output:

    head <Link to={Django.url('reservation:manual:product:index')}></Link> tail