Cookbook

Small recipes for common tasks. Copy them into src/plugins/main.lua and your templates.

Shared head

Put the repeated tags in a template and include it from every page.

src/templates/head.md:

{% document title=page_title lang="en" %}
{% meta name="viewport" content="width=device-width, initial-scale=1" %}
{% style "static/style.css" %}

A page:

{% set page_title = "About" %}
{% include "head.md" %}

# About

Text.

A menu from a Lua list

Keep the page list in one place, main.lua:

merodi.jinja.set("pages", {
	{ url = "index.html", title = "Home" },
	{ url = "about.html", title = "About" },
})

merodi.hook("before_read", function()
	local name = merodi.build.md_path.get():match("([^/]+)%.md$")
	merodi.jinja.set("current", name .. ".html")
end)

src/templates/menu.md is a plain Markdown list. The current page is bold instead of a link:

{%- for p in pages %}
{% if p.url == current %}- **{{ p.title }}**{% else %}- [{{ p.title }}]({{ p.url }}){% endif %}
{%- endfor %}

Add {% include "menu.md" %} where the menu should appear. The - in {%- removes the blank lines the loop would leave, so the list stays one tight list.

Add a charset meta tag

The meta tag writes only name and content, so it cannot make <meta charset>. Add it to the finished page instead:

merodi.hook("doc_content", function()
	local html = merodi.build.content.get()
	merodi.build.content.set((html:gsub("<head>", '<head>\n<meta charset="utf-8">', 1)))
end)

Skip drafts in a release build

Keep unfinished pages in src/md/drafts/. They build in draft mode and are skipped in release mode:

merodi.hook("before_read", function()
	local path = merodi.build.md_path.get()
	if merodi.build.mode() == "release" and path:find("/drafts/", 1, true) then
		merodi.abort()
	end
end)

Put the build date in a page

merodi.jinja.set("built", os.date("%Y-%m-%d"))
Built on {{ built }}.

Rebuild when files change

watch calls your hook and you run the build:

merodi.watch.add("src/md")
merodi.watch.add("src/templates")

merodi.hook("on_file_changed", function(mode, path)
	if mode:find("WRITE") then
		os.execute("merodi build")
	end
end)

Run merodi watch in one terminal. Add one merodi.watch.add per subfolder, because folders are not watched recursively.

Deploy with your own command

merodi.hook("deploy", function(target)
	if not target then
		merodi.log.die("usage: merodi hook deploy user@host:/path/")
	end
	os.execute("rsync -av --delete build/release/ " .. target)
end)
merodi build --release
merodi hook deploy me@example.com:/var/www/site/

Write a page to another file name

merodi.hook("before_write", function()
	local out = merodi.build.document_path.get()
	merodi.build.document_path.set((out:gsub("%.html$", ".htm")))
end)

Convert Markdown inside Lua

merodi.enable.GFM()
local html = merodi.compile.mdtohtml("| a | b |\n|---|---|\n| 1 | 2 |")
merodi.log.info(html)