From f49bcc0bfc5bf7240b846074c2683f9628ca1838 Mon Sep 17 00:00:00 2001 From: leaf corcoran Date: Sat, 1 Feb 2014 12:36:47 -0800 Subject: [PATCH] add documentation for raw api --- README.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/README.md b/README.md index 3fb706f..6fba3c1 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,77 @@ message. * The parser is aware of strings so you can put closing tags inside of a string literal without any problems. +## Raw API + +The raw API is a bit more complicated but it lets you insert code between the +compile stages in addition to exposing the internal buffer of the template. + +All methods require a parser object: + +```lua +local parser = etlua.Parser() +``` + +#### `lua_code, err = parser.compile_to_lua(etlua_code)` + +Parses a string of etlua code, returns the compiled Lua version as a +string. + +Here's an example of generated code for the example script: + +```lua +local parser = etlua.Parser() +print(parser:compile_to_lua("hello<%= world %>")) +``` + +```lua +local _b, _b_i, _tostring, _concat, _escape = ... +_b_i = _b_i + 1 +_b[_b_i] = "hello" +_b_i = _b_i + 1 +--[[9]] _b[_b_i] = _escape(_tostring( world )) +_b_i = _b_i + 1 +_b[_b_i] = "" +return _b +``` + +There are a few interesting things, there are no global variable references, +all required values are passed in as arguments. Comments are inserted to +annotate the positions of where code originated from. `_b` is expected to be a +regular Lua table that is the buffer where chunks of the template are inserted +into. + +#### `fn, err = parser.load(lua_code)` + +Converts the Lua code returned by `parser.compile_to_lua` into an actual +function object. If there are any syntax errors then `nil` is returned along +with the error message. At this stage, syntax errors are rewritten to point to +the original location in the etlua code and not the generated code. + +#### `result = parser.run(fn, env={}, buffer={})` + +Executes a loaded function returned by `parser.load` with the specified buffer +and environment. Returns the result of fn, which is typically the buffer. The +environment is applied to `fn` with `setfenv` (a version is included for Lua +5.2). + +### Example + +For example we can render multiple templates into the same buffer: + +```lua +parser = etlua.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) + +print(table.concat(buffer)) -- print 'Hello World' +``` + ## License MIT, Copyright (C) 2013 by Leaf Corcoran