Nov 05, 2014 Tag: ReST

Customization options of text roles

Huh - what is this? You may know that directives can have options, but text roles? You’re right. They don’t have options. But they can have customization options. And this post is about what fancy stuff you can do with it.

Keywords: ReST, text roles, interpreted text, Docutils, Sphinx

What are text roles?

ReST has the notion of interpreted text which is text that starts with a backtick and ends with a backtick. That text is interpreted according to a role which is usually given explicitely:

:title:`Rock around the clock`
or
`Rock around the clock`:title:

That looks very clear: We are dealing with the title of something.

And there is a default-role directive that lets you set a default role so you don’t have to specify it explicitely.

Source:

.. default-role:: code

You can rewrite `y = 2x + 1` as `y - 1 = 2x`

.. default-role:: emphasis

Two guys you should remember: `Guido` and `David`

Result:

You can rewrite y = 2x + 1 as y - 1 = 2x.

Two guys you should remember: Guido and David.

Customization options

Admitted: The Docutils documentation can be difficult to understand: Reading about the raw text role for example - what does customization options: class, format mean?

The answer is given in the examples and relies on these facts:

  1. ReST has a directive role that lets you create new text roles on the fly.

  2. Those new text roles can inherit from an existing one.

  3. And now we get to the point:

    You can tailor the new text role by specifying legal customization options of the role you inherit from in the role directive.

Are you still there? That sounds complicated. But in fact it’s very easy once you see an example:

.. role:: raw-html(raw)
   :format: html singlehtml

Here we create a new text role raw-html. It inherits the functionality of the built in text role raw. And additionally it’s being customized by the option “format” which tells the new text role to only function when the writer is either “html” or “singlehtml”.

In other words: We now have a text role that lets us insert HTML raw code right in our ReST source. And this will not interfere with - let’s say - latex output.

You get the idea?

Let’s use it!

First we define the raw-html text role for HTML output. And we add a substitution definition for the word “smile” that inserts HTML code to show a “smile” icon of the Fontawesome font:

.. role:: raw-html(raw)
   :format: html

.. |smile| replace:: :raw-html:`<span class="fa fa-smile-o"></span>`

Done!

Now you can easily “smile”:

Smile for me |smile| and smile for you |smile|!

Result:

Smile for me and smile for you !

Isn’t that great?

Tip: Don’t overuse the technique. Keep your sources readable!

Comments

comments powered by Disqus

Previous topic

Using Git

Next topic

TYPO3-Camp Rhein-Ruhr 2014

Tags

Archives

Languages

Recent Posts

This Page