# HG changeset patch # User Matthew Wild # Date 1687465535 -3600 # Node ID 635b385df3a2be660d80a5e89111f112c686207c # Parent 0578564f8612cbaa40af6ee5b465f4b8899bb012 templates: Support for templates that extend other templates diff -r 0578564f8612 -r 635b385df3a2 src/templates.lua --- 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;