"><%label%> 論理構造 2 then ?>

Luaでテンプレートをコンパイルするためのワンライナー

Lua構文を使用すると、わずかな正規表現を使用してPHPスタイルのテンプレートを実装できます。
まず、何が起こるか見てみましょう。

変数置換


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

論理構造


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

サイクル


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


他のテンプレートを接続する


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

<? 「追跡」が必要ですか?>

そして、Lua上のその他の構成体


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

そして、これらはすべて、通常のLuaモジュールの1つのコマンドによって収集されます。
 (echo 'return function(_)_[=['; sed -e 's/[][]=[][]/]=]_"\0"_[=[/g; s/<%/]=]_(/g; s/%>/)_[=[/g; s/<[?]/]=] /g; s/[?]>/ _[=[/g'; echo ']=] end') < template.tpl > template.lua 

実際、実行するには、別の短い関数を記述する必要があります。
 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 

設置


Moon Rocksには、3つの関数の小さなライブラリがあります。
 luarocks install template 

luarocksは、 Ubuntuリポジトリで利用可能です。
 sudo apt-get install luarocks 

GitHubのプロジェクト


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


All Articles