Skip to content
Snippets Groups Projects
Commit c407e96e authored by Josh Borrow's avatar Josh Borrow
Browse files

Added ability for templates to have individual data files

parent f37ade97
Branches
No related tags found
No related merge requests found
- title: "Hello World"
date: "19th June 1995"
img: "helloworld.png"
cards:
- title: "Hello World"
date: "19th June 1995"
img: "helloworld.png"
- title: "Hello Dogs"
date: "18th June 1994"
img: "hellodogs.png"
\ No newline at end of file
- title: "Hello Dogs"
date: "18th June 1994"
img: "hellodogs.png"
\ No newline at end of file
......@@ -10,17 +10,42 @@ import jinja2
import yaml
def get_from_filesystem(template_names, template_dir="."):
""" Takes a list of template names and returns a list of template objects
that are ready for rendering. """
def get_from_filesystem(template_names, template_dir=".", data_dir="../data"):
""" Takes a list of template names and returns a zipped list of template
objects and associated data values that are ready for rendering wih the
render_template function. """
template_loader = jinja2.FileSystemLoader(searchpath=template_dir)
template_env = jinja2.Environment(loader=template_loader)
return list(map(template_env.get_template, template_names))
templates = list(map(template_env.get_template, template_names))
data = get_associated_data(template_names, data_dir)
return zip(templates, data)
def render_template(template, data_dir="../data", args={}):
def get_associated_data(template_names, data_dir="../data"):
""" Grabs the data from yaml files within the data directory if they exist,
and if not returns an empty dictionary for that item. """
data = []
for template in template_names:
# swap that .html for a .yaml
stub = template.split(".")[0]
filename = f"{data_dir}/{stub}.yaml"
try:
with open(filename, "r") as f:
data.append(yaml.load(f))
except FileNotFoundError:
data.append({})
return data
def render_template(template, args, data_dir="../data"):
""" Args is a dictionary of the local variables required for
rendering the template. """
......@@ -68,8 +93,8 @@ def global_variables(active, data_dir="../data"):
def render(render_pages, data_dir, template_dir, output_dir):
""" Main rendering function for all of the pages. """
templates = get_from_filesystem(render_pages, template_dir)
output = [render_template(page, data_dir) for page in templates]
data = get_from_filesystem(render_pages, template_dir)
output = [render_template(page, args, data_dir) for page, args in data]
# Save the files into the output_dir
if not os.path.exists(output_dir):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment