📜 ⬆️ ⬇️

One-liner to compile Lua templates

Lua syntax allows you to implement php-style patterns with just a few regular expressions.
First, let's see what happens.

Variable substitution


<a href="<%url%>"><%label%></a> 

Logical constructions


  <? if 1 > 2 then ?>  <? else ?>  <? end ?> 

Cycles


 <ul> <? for i = 1, 9999 do ?> <li><%i%></li> <? end ?> </ul> 


Connecting other templates


 <html> <script><? require "scripts" ?></script> <style><? require "styles" ?></style> ... 

<? require 'tracking'?>

And any other designs on Lua


 <? function warn() ?> <b>    !</b> <? end ?> ... <? warn() ?> ... <? --[[ ?>    <? --]] ?> 

And this is all going to one team in a regular module Lua:
 (echo 'return function(_)_[=['; sed -e 's/[][]=[][]/]=]_"\0"_[=[/g; s/<%/]=]_(/g; s/%>/)_[=[/g; s/<[?]/]=] /g; s/[?]>/ _[=[/g'; echo ']=] end') < template.tpl > template.lua 

In fact, to run, you need to write another short function:
 function template.print(data, args, callback) local callback = callback or print local function exec(data) if type(data) == "function" then local args = args or {} setmetatable(args, { __index = _G }) setfenv(data, args) data(exec) else callback(tostring(data)) end end exec(data) end 

Installation


A small library of three functions is available at Moon Rocks :
 luarocks install template 

luarocks , in turn, is available in the Ubuntu repositories:
 sudo apt-get install luarocks 

Project on github .

')

Source: https://habr.com/ru/post/243321/


All Articles