Automatically insert data into a reStructuredText file
Suppose you need to present three products: Dianthus, Geum, and Prunus, each available in versions 1.0, 1.5, and 2.3.
Instead of manually entering data into the content file, you can automate this process using Jinja and Python.
-
Create the following
template.rstfile:Products and Versions====================={% for prod in products %}{{ prod | capitalize }}{% for c in prod %}-{% endfor %}{% for ver in versions %}- {{ ver }}{% endfor %}{% endfor %} -
Create the following Python script
populate.py:#!/usr/bin/python# coding: utf-8import jinja2env = jinja2.Environment(loader=jinja2.FileSystemLoader('./'))template = env.get_template('template.rst')data = {'products': ['dianthus', 'geum', 'prunus'],'versions': ['1.0', '1.5', '2.3']}print(template.render(data)) -
Make the script executable, then run it:
Terminal window chmod +x populate.py./populate.pyThe following output is displayed:
Products and Versions=====================Dianthus--------- 1.0- 1.5- 2.3Geum----- 1.0- 1.5- 2.3Prunus------- 1.0- 1.5- 2.3
This approach minimizes the risk of errors and reduces the effort involved in updating.
Additional resources