templates: Support for templates that extend other templates

Thu, 22 Jun 2023 21:25:35 +0100

author
Matthew Wild <mwild1@gmail.com>
date
Thu, 22 Jun 2023 21:25:35 +0100
changeset 11
635b385df3a2
parent 10
0578564f8612
child 12
dfa7cb60647e

templates: Support for templates that extend other templates

src/templates.lua file | annotate | diff | comparison | revisions
--- a/src/templates.lua	Wed Nov 24 16:18:19 2021 +0000
+++ b/src/templates.lua	Thu Jun 22 21:25:35 2023 +0100
@@ -2,26 +2,41 @@
 
 local function readfile(filename)
 	local fh = assert(io.open(filename));
-	local data = fh:read("*a");
+	local data, err = fh:read("*a");
+	if not data then
+		return error(filename..": "..err);
+	end
 	fh:close();
 	return data;
 end
 
-local _M = {};
+local template_base_path = (os.getenv("TEMPLATE_PATH") or ".").."/";
 
-local template_base_path = (os.getenv("TEMPLATE_PATH") or ".").."/";
+local function read_template_file(template_path, filename)
+	local template = readfile(template_path.."/"..filename);
+	if template:sub(1,9) == "#EXTENDS:" then
+		local parent_template, pragma_end = template:match("^#EXTENDS: *([^\r\n]+)\r?\n()");
+		template = template:sub(pragma_end);
+		local base_template = read_template_file(template_path, parent_template);
+		template = base_template:gsub("{SUBTEMPLATE}", ((template):gsub("%%", "%%%%")));
+	end
+	return template;
+end
+
+local _M = {};
 
 function _M.init(config)
 	local templates = {};
 
 	local template_path = template_base_path..(config.templates or "html");
-
 	for filename in lfs.dir(template_path) do
-		local template_name = filename;
-		if filename:match("%.html$") then
-			template_name = filename:gsub("%.html$", "");
+		if filename:sub(1,1) ~= "." then
+			local template_name = filename;
+			if filename:match("%.html$") then
+				template_name = filename:gsub("%.html$", "");
+			end
+			templates[template_name] = read_template_file(template_path, filename);
 		end
-		templates[template_name] = readfile(template_path.."/"..filename);
 	end
 
 	return templates;

mercurial