diff --git a/etlua.lua b/etlua.lua index fd28bac..7bc5ca9 100644 --- a/etlua.lua +++ b/etlua.lua @@ -264,6 +264,13 @@ do setfenv(fn, combined_env) return fn(buffer, #buffer, tostring, concat, html_escape) end, + compile_to_lua = function(self, str) + local success, err = self:parse(str) + if not (success) then + return nil, err + end + return self:chunks_to_lua() + end, chunks_to_lua = function(self) local buffer = { "local _b, _b_i, _tostring, _concat, _escape = ..." diff --git a/etlua.moon b/etlua.moon index b8708dd..748d2b0 100644 --- a/etlua.moon +++ b/etlua.moon @@ -199,6 +199,11 @@ class Parser setfenv fn, combined_env fn buffer, #buffer, tostring, concat, html_escape + compile_to_lua: (str) => + success, err = @parse str + return nil, err unless success + @chunks_to_lua! + -- generates the code of the template chunks_to_lua: => -- todo: find a no-conflict name for locals diff --git a/spec/etlua_spec.moon b/spec/etlua_spec.moon index 1566c8c..7e4e97c 100644 --- a/spec/etlua_spec.moon +++ b/spec/etlua_spec.moon @@ -112,6 +112,18 @@ This is my message to <%= [=[oh yeah %>"]=] %>]] out = fn {}, buff assert.same "firsthelloyeah", out + it "should compile readme example", -> + parser = Parser! + + first_fn = parser\load parser\compile_to_lua "Hello " + second_fn = parser\load parser\compile_to_lua "World" + + buffer = {} + parser\run first_fn, nil, buffer + parser\run second_fn, nil, buffer + + assert.same "Hello World", table.concat buffer + describe "Parser.in_string", -> cases = { { "hello world", false }