RenderScripts

Introduction to RenderScripts – create web pages using python

RenderScripts are regular Python scripts, except that:

These scripts are run when your site is rendered. Anything that they print to stdout becomes a new file in your site. The name of the file is the same as the name of the .py script, without the .py extension. For instance, the page you're reading right now is created by renderscript.md.py, which you'll find here.

Hot/live reloading even works with these .py scripts – so as soon as you save the script, you'll see the new output in your web browser.

This approach can be particularly helpful for generating data-driven documents. For instance, consider this table, containing a list of the people with testimonials on fastship's home page:

NamePosition
Chris LattnerInventor of Swift and LLVM
Fernando PérezCreator of Jupyter
David BergSoftware Engineer, Netflix
Erik GaasedelenSoftware Engineer, Lyft
Roxanna PourzandProduct Manager, Transform
Hugo Bowne-AndersonHead of Developer Relations, Outerbounds

When creating a table like this, it can be tricky to ensure that markdown is correct and consistent for every row. It can be easier and more maintainable to programatically generate it. The table above is generated from the following python list:

testimonials = [
    ('chris-lattner.png', 'Chris Lattner', 'Inventor of Swift and LLVM'),
    ('fernando-pérez.jpeg', 'Fernando Pérez', 'Creator of Jupyter'),
    ('david-berg.jpeg', 'David Berg', 'Software Engineer, Netflix'),
    ('erik-gaasedelen.jpeg', 'Erik Gaasedelen', 'Software Engineer, Lyft'),
    ('roxanna-pourzand.jpeg', 'Roxanna Pourzand', 'Product Manager, Transform'),
    ('hugo-bowne-anderson.jpeg', 'Hugo Bowne-Anderson', 'Head of Developer Relations, Outerbounds')
]

To produce the table from this python list, the following four lines of code are used:

print(row(['', 'Name', 'Position']))
print(row(['---', '---', '---']))
for fname, name, position in testimonials:
    print(row([im(fname, 60), name, position]))

For richer HTML layouts and reusable components, use fastcore.xml tags (Div, Img, P, to_xml) directly — see _index.py and index.qmd behind the fastship home page.

You can use RenderScripts to create any kind of file. For instance, the SVG below is created dynamically using this script:

Once you've run ship-preview or ship-docs you'll find your rendered output in _docs/. You can also run your script directly from the shell (e.g. python renderscript.md.py) to inspect the generated Markdown.