lua-users home
lua-l archive

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





On Wed, Jan 8, 2014 at 5:16 AM, Alexander Gladysh <agladysh@gmail.com> wrote:
Hi, list!

Everyone is familiar with text templates. One of the most popular
examples is {{mustache}} [1] [2].

Now and then I find myself writing data transformation code that would
benefit from a similar template technique.

For example, I may write something like this:

local data =""> {
  { "foo.png", 42, 24 };
  { "bar.png", 0, 10 };
  { "baz.png", 314, 1 };
}

local result = { }
for i = 1, #data do
  result[#result + 1] =
  {
    sprite = "/img/" .. data[1];
    x = data[2], y = data[3];
  }
end

(Actual code and data structures are, of course, usually somewhat more
complicated than this.)

I'd like to write this declaratively. Maybe like this:

local result = T:map (data)
{
  sprite = "/img/" .. T(1);
  x = T(2), y = T(3);
}

Before I go ahead and reinvent the wheel, I wonder, is there something
along these lines out there?

Alexander.

[1] http://mustache.github.com/
[2] http://olivinelabs.com/lustache/


Well I did steal this from zxc on github... https://github.com/Pogs/mustache.lua

It's mostly the same as what he wrote, I just changed a few things like converting a few loops to make use of gsub.  I sort of gave up on it (though I trust it), as I fell out of love with mustache.  The only things missing are partials and the ability to change delimiters.  I added the extension:

{{?section}}printed only once, even if list{{/section}}

Templating is a fun topic to be sure :-)

PS: I never saw the point of having partial templates because I never needed them, I'm sure to large codebases it would make sense.  I just didn't put in the work to add that.  I also gave up on changing delimiters because of how I'd need to break the gsub() loop to reparse with the new delimiter.  Perhaps there is an easy solution to that, but I never needed other delimiters so I didn't do that either...   (I'm selfish)

PPS: Here's what I did beyond zxc's work: https://github.com/Pogs/mustache.lua/commits/master