src/templates.lua

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 0
6279a7d40ae7
permissions
-rw-r--r--

templates: Support for templates that extend other templates

local lfs = require "lfs";

local function readfile(filename)
	local fh = assert(io.open(filename));
	local data, err = fh:read("*a");
	if not data then
		return error(filename..": "..err);
	end
	fh:close();
	return data;
end

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
		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
	end

	return templates;
end

return _M;

mercurial