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.
Objective
Section titled “Objective”The profiling.py Python script below allows you to profile content in preprocessing using the powerful Jinja template engine.
-
Create the
profiling.pyscript:#!/usr/bin/env python3import jinja2import syspublic=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() -
Create the content file
conditional-text.rst:Using conditional text================================={% if audience=='electrician' %}.. admonition:: Danger for electriciansRisk of electrocutionDo not touch electrical wires.{% else %}.. admonition:: Danger for plumbersRisk of drowningDo not dive into the pool.{% endif %} -
Run the script with the audience as parameter:
Terminal window ./profiling.py electricianThe script writes the version of the content for this audience to
conditional-text-output.rst. -
Call the script before compiling via Sphinx in the
Makefile.
Next steps
Section titled “Next steps”- For a more complex variant using object-oriented classes, see creating different documents via Jinja (object method).
- You can also generate documents directly from ReST conditional text without a separate preprocessing step.