Jinja Templates

Basic Setup

  1. Create a folder containing all your templates

    templates
    ├── layout.html
    ...
    └── links.html
    
  2. Create an Environment with an appropriate loader so that jinja is able to find the templates.

    import jinja2 as j2
    
    loader = j2.FileSystemLoader(templates_dir)
    env = j2.Environment(loader=loader)
    
  3. Load the relevant template(s) from the environment

    template = env.get_template("layout.html")
    
  4. Create the context containing the variables that are passed down into the template.

    context = {
       "date": datetime.now(),
       "author": "S. King",
       "word_count": float("inf")
    }
    
  5. Render the template!

    with open(filename, "w") as f:
       f.write(template.render(context))