lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I am refactoring an existing template engine.  The basic idea is to convert a template
into Lua code using a luaL_reader C function that reads template code, converts it to
Lua source code and hands it to the Lua loader function.  This way, templates become
Lua chunks which are run to render the template.  A bit like PHP and Django, but
using Lua.

In a previous version, I used a separate Lua state to run the template code and a proxy
module to populate the render state with the variables I want the templates to have access
to.  That works nicely.

Now I want to do it a single state and hand a table to the rendering function, with the
idea that the functions called have only access to the variable in the table, as if they
were globals:

local ctx = template.context()
local data = {}

data.value = 42;
data.title = 'Hello, world!'

ctx:render('sample.lt', data)

So far I did not succeed.  I assume that I have to set _ENV for each chunk that possibly
runs during template rendering (it can be many, and the idea is to call them repeatedly using
different data tables).  So this would mean to fixup _ENV for each chunk everytime the
render() function is called?  Or can I temporarily swap globals?

For now I think I will have to hand the data table when I create the context, so each time
a chunk is loaded, I already have a handle to it and can assign it as _ENV for each chunk
I load:

local data = {}
local ctx = template.context(data)

data.value = 42;
data.title = 'Hello, world!'

ctx:render('sample.lt')

Ideas or comments appreciated!

Thnks, Marc