Refactor code to use Jinja templates

This commit produces exactly the same output as the previous one.