Recreate the forPrefix hook in page templates

I also liked the original method of having metadata in the template file.
So following on from how command is implemented for a template I used a query to create the event listeners. I did have the same issue that others had where the page isn’t templated quite the same and the cursor isn’t moved (compare to using the command or shortcut key).
The below will add the handler from any meta/template/page tagged file with the forPrefix field present.

-- based on createPageFromTemplate but return the string
local function returnPageFromTemplate(templatePage)
  local tpl, fm = template.fromPage(templatePage)
  local initialText = ""
  if fm.frontmatter then
    initialText = "---\n"
      .. string.trim(template.new(fm.frontmatter)())
      .. "\n---\n"
  end
  return initialText .. tpl()
end

-- Create event handler for all page templates with a forPrefix key in frontmatter
for pt in query[[
    from index.tag "meta/template/page"
    where _.tag == "page" and _.forPrefix
    order by _.priority desc
  ]] do
  event.listen {
    name = "editor:pageCreating",
    run = function(e)
      if e.data.name:startsWith(pt.forPrefix) then
        return {
          text = returnPageFromTemplate(pt.name)
        }
      end
    end
  }
end
2 Likes