Skip to content

Commit

Permalink
add documentation for raw api
Browse files Browse the repository at this point in the history
  • Loading branch information
leafo committed Feb 1, 2014
1 parent e81c4e4 commit f49bcc0
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit f49bcc0

Please sign in to comment.