Search code examples
python-sphinxrestructuredtextconditional-compilation

What's the difference between Sphinx's "only" and "ifconfig" directives?


Sphinx knows two directives for conditional content:

What's the difference between them?


Solution

  • only

    The only directive is used to include/exclude content based on tags. tags can be specified:

    1. In the conf.py (this use makes only pretty similar to ifconfig)
    2. Using the -t flag to sphinx-build (doesn't work as a flag to make because -t is the --touch flag for make)

      example.rst

      .. only:: draft
      
         This message only appears in drafts.
      

      command

      $ sphinx-build  -t draft  -b html -d _build/doctrees . _build/html
      
    3. The format or name of builder. This is where only shines. .. only:: html contents would only get built when you use make html etc.

      example.rst

      .. only:: html
      
         This message only appears in HTML output.
      

      command

      $ make html
      

    ifconfig

    ifconfig gives you the flexibility to include content based on the true-ness of any Python expression involving configuration variables registered in conf.py. This means, though, that you have to edit the conf.py to change whether content is included or excluded.

    Conclusion

    If you want your content to change without editing conf.py you want only. For example, I use only to include a table of contents (contents directive) in my HTML docs, but not in my pdf docs (because LaTeX produces those on its own).