Skip to content

Create different documents from the same sources using Jinja

Profile reStructuredText content with Jinja and a Python preprocessing script to generate audience-specific document variants - user, admin, lite - from a single source.

, 1 min read

The profiling.py Python script below allows you to profile content in preprocessing using the powerful Jinja template engine.

  1. Create the profiling.py script:

    #!/usr/bin/env python3
    import jinja2
    import sys
    public=str(sys.argv[1])
    env = jinja2.Environment(loader=jinja2.FileSystemLoader('./'))
    template = env.get_template('conditional-text.rst')
    string=template.render(audience=public)
    file = open('conditional-text-output.rst','w')
    file.write(string)
    file.close()
  2. Create the content file conditional-text.rst:

    Using conditional text
    =================================
    {% if audience=='electrician' %}
    .. admonition:: Danger for electricians
    Risk of electrocution
    Do not touch electrical wires.
    {% else %}
    .. admonition:: Danger for plumbers
    Risk of drowning
    Do not dive into the pool.
    {% endif %}
  3. Run the script with the audience as parameter:

    Terminal window
    ./profiling.py electrician

    The script writes the version of the content for this audience to conditional-text-output.rst.

  4. Call the script before compiling via Sphinx in the Makefile.