ferron

[ARCHIVED] Ferron is a fast and simple static website generator made with Lua.
Log | Files | Refs | Submodules | README | LICENSE

template-utils.lua (1763B)


      1 -- templateutils.lua
      2 local templateutils = {}
      3 local templateutilsmeta = {
      4   __call = function(self, key, vars)
      5     print(key)
      6   end
      7 }
      8 
      9 local lfs = require 'lfs'
     10 local lustache = require 'lustache'
     11 local site = require 'ferron.site'
     12 local fl = require 'ferron.utilities.file-utils'
     13 
     14 -- set template
     15 function templateutils.selecttemplate(index, templatename, templatesdir)
     16   local templatepath = templatesdir .. '/'
     17   local template
     18 
     19   if templatename and type(templatename) == 'string' then
     20     template = templatepath .. templatename
     21   else
     22     if type(index) == 'boolean' and index == true then
     23       template = templatepath .. 'default-index'
     24     else
     25       template = templatepath .. 'default'
     26     end
     27   end
     28 
     29   return assert(template .. '.mustache', 'You need to add some templates to your site.')
     30 end
     31 
     32 -- process mustache
     33 function templateutils.rendermustache(tpl, data)
     34   local partials = {}
     35   local partialspath = fl.isDirectory(site.templates) .. '/partials'
     36 
     37   for _, v in ipairs(lustache:parse(tpl)) do
     38     if v.type == '>' then
     39       partials[v.value] = fl.pullfilecontent(partialspath .. '/' .. v.value .. '.mustache')
     40     end
     41   end
     42 
     43   return lustache:render(tpl, data, partials)
     44 end
     45 
     46 -- process template
     47 function templateutils.rendertemplate(template, data)
     48   local render
     49 
     50   if fl.getextension(template) == '.mustache' then
     51     render = templateutils.rendermustache(fl.pullfilecontent(template), data)
     52   end
     53 
     54   return render
     55 end
     56 
     57 -- get template path
     58 function templateutils.gettemplatepath(pagepath, sitedata)
     59   local dir = lfs.currentdir() .. '/' .. sitedata.templates
     60   local name = (fl.getpageconf(pagepath).template or 'default')
     61 
     62   return  fl.isFile(dir .. '/' .. name  .. '.mustache')
     63 end
     64 
     65 return setmetatable(templateutils, templateutilsmeta)