Commit a297a904 authored by Joseph Walton-Rivers's avatar Joseph Walton-Rivers 🍪

code for loading data files

parent 03abab44
Pipeline #1379 failed with stages
in 49 seconds
......@@ -4,6 +4,7 @@ import pathlib
import shutil
from j2static import build
from j2static.tools.merge import load_data
def find_all(dirpath):
files = []
......@@ -14,8 +15,9 @@ def find_all(dirpath):
files.extend( find_all(path) )
return files
def generate(args, outdir='site/'):
def generate(args, datadir='_data', outdir='site/'):
out_path = pathlib.Path(outdir)
data_path = pathlib.Path(datadir)
template_path = pathlib.Path(args.template_dir)
generator = build.get_builder("html", args.template_dir)
......@@ -23,8 +25,15 @@ def generate(args, outdir='site/'):
for path in find_all(template_path):
relative_path = path.relative_to(template_path)
out_file = out_path / relative_path
if generator.filter(path):
generator.generate(str(relative_path), out_file)
context = []
data_file = data_path / (relative_path.stem + ".json")
if data_file.exists():
context = load_data(data_file)
generator.generate(str(relative_path), out_file, context=context)
elif path.is_file() and relative_path.name[0] != '_':
out_file.parent.mkdir(exist_ok=True, parents=True)
shutil.copy(path, out_file)
......@@ -12,11 +12,13 @@ import shutil
import jinja2
from j2static.build import get_builder
from j2static.tools.merge import load_data
from http.server import HTTPServer, BaseHTTPRequestHandler
PORT = 8080
TEMPLATE_DIR = "_templates/"
DATA_DIR = pathlib.Path("./_data/")
class TemplateHTTPServer(BaseHTTPRequestHandler):
......@@ -31,7 +33,15 @@ class TemplateHTTPServer(BaseHTTPRequestHandler):
builder = get_builder("html", TEMPLATE_DIR)
if builder.filter(file_path):
try:
data = builder.render(file_path)
context = []
template_path = pathlib.Path(file_path[1:])
data_file = DATA_DIR / template_path.parent / (template_path.stem + ".json")
if data_file.exists():
context = load_data(data_file)
data = builder.render(file_path, context=context)
self.send_response(200)
self.send_header('Content-type', 'text/html')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment