• Stars
    star
    200
  • Rank 188,244 (Top 4 %)
  • Language
    Lua
  • Created over 10 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Embedded Lua templates

etlua

Embedded Lua templating

Install

$ luarocks install etlua

Tutorial

local etlua = require "etlua"
local template = etlua.compile([[
  Hello <%= name %>,
  Here are your items:
  <% for i, item in pairs(items) do %>
   * <%= item -%>
  <% end %>
]])

print(template({
  name = "leafo",
  items = { "Shoe", "Reflector", "Scarf" }
}))

Reference

The following tags are supported

  • <% lua_code %> runs lua code verbatim
  • <%= lua_expression %> writes result of expression to output, HTML escaped
  • <%- lua_expression %> same as above but with no HTML escaping

Any of the embedded Lua tags can use the -%> closing tag to suppress a following newline if there is one, for example: <%= 'hello' -%>.

The module can be loaded by doing:

local etlua = require "etlua"

Methods

func = etlua.compile(template_string)

Compiles the template into a function, the returned function can be called to render the template. The function takes one argument: a table to use as the environment within the template. _G is used to look up a variable if it can't be found in the environment.

result = etlua.render(template_string, env)

Compiles and renders the template in a single call. If you are concerned about high performance this should be avoided in favor of compile if it's possible to cache the compiled template.

Errors

If any of the methods fail they will return nil, followed by the error message.

How it works

  • Templates are transparently translated into Lua code and then loaded as a function. Rendering a compiled template is very fast.
  • Any compile time errors are rewritten to show the original source position in the template.
  • 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:

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 the generated Lua code:

local parser = etlua.Parser()
print(parser:compile_to_lua("hello<%= world %>"))
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, and 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 as it's executed.

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:

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, #buffer)
parser:run(second_fn, nil, buffer, #buffer)

print(table.concat(buffer)) -- print 'Hello World'

Custom compiler

If you need to customize the Lua code that is generated by etlua to integrate with your own output buffers then you can provide a custom compiler.

You can extend etlua.Compiler and override it's methods to control the output. See https://github.com/leafo/etlua/blob/master/etlua.moon#L42 for the implementation of the default compiler

For an example we'll create a debug compiler that prints whenever a template is executed.

-- create a custom compiler
import Compiler from require "etlua"

class DebugCompiler extends Compiler
  header: =>
    @push 'print("Running template")\n'
    super!

-- try it out
import Parser from require "etlua"

print Parser!\compile_to_lua "hello", DebugCompiler

compile_to_lua takes an optional second argument of the compiler class to use.

Editor Support

License

MIT, Copyright (C) 2014 by Leaf Corcoran

More Repositories

1

moonscript

🌙 A language that compiles to Lua
Lua
3,026
star
2

lapis

A web framework for Lua and OpenResty written in MoonScript
MoonScript
2,923
star
3

sticky-kit

A jQuery plugin for creating smart sticky elements
CoffeeScript
2,919
star
4

lessphp

LESS compiler written in PHP
PHP
2,210
star
5

scssphp

SCSS compiler written in PHP
PHP
1,351
star
6

sightreading.training

🎹 Sight reading training tool
JavaScript
404
star
7

magick

Lua bindings to ImageMagick for LuaJIT using FFI
Lua
383
star
8

pgmoon

A pure Lua Postgres driver for use in OpenResty & more
MoonScript
376
star
9

gifine

Quickly record and edit gifs and videos of your desktop
Lua
283
star
10

aroma

a game engine: lua, opengl es 2.0, native client
C
197
star
11

streak.club

a website for running creative streaks
MoonScript
133
star
12

tableshape

Test the shape or structure of a Lua table, inspired by React.PropTypes & LPeg
MoonScript
110
star
13

gifserver

A server for transcoding gif to video on the fly
Go
102
star
14

lovekit

Miscellaneous code for making games in LOVE with MoonScript
Lua
96
star
15

moonscript-vim

MoonScript support for vim
Vim Script
96
star
16

lua-enet

Bindings to ENet for Lua
C
85
star
17

heroku-openresty

Run OpenResty on Heroku with the Lua buildpack
Lua
78
star
18

sitegen

static site generator in MoonScript
Lua
76
star
19

lua-payments

Various payment provider APIs for Lua (and OpenResty): Stripe, PayPal
MoonScript
71
star
20

web_sanitize

Lua library for sanitizing, parsing, and editing untrusted HTML
MoonScript
70
star
21

gh-actions-lua

GitHub action for Lua/LuaJIT
JavaScript
70
star
22

moonlisp

a Lisp that compiles to Lua
C
67
star
23

scssphp-compass

Compass for scssphp
PHP
66
star
24

image-server-tutorial

An example of an image processing server in OpenResty and Lua
Lua
65
star
25

compohub

A website for listing game jams
CoffeeScript
61
star
26

itchio-app-old

Desktop itch.io client
C++
45
star
27

lapis-community

Pluggable message board for Lapis powered websites
MoonScript
44
star
28

goattracker2

a fork of goattracker2
C
42
star
29

loadkit

Loadkit allows you to load arbitrary files within the Lua package path
MoonScript
41
star
30

gh-actions-luarocks

GitHub action for installing LuaRocks
JavaScript
40
star
31

lapis-console

Interactive console for working with Lapis
Lua
40
star
32

cloud_storage

A Lua library for communicating with Google Cloud Storage
Lua
40
star
33

moonscript-javascript

MoonScript compiled to JavaScript with Emscripten
JavaScript
38
star
34

moonscript-tmbundle

textmate support for MoonScript
37
star
35

lua-openai

OpenAI API bindings for Lua
MoonScript
37
star
36

lapis-bayes

Naive Bayes classifier for use in Lua
Lua
30
star
37

moonrocks

command line tool for working with rocks.moonscript.org
Lua
29
star
38

lua-twitter

A Lua twitter library that works with OpenResty or LuaSocket
Lua
27
star
39

lua-mailgun

Lua bindings to Mailgun HTTP API
MoonScript
25
star
40

ludum-dare-browser

a website for browsing ludum dare games
HTML
25
star
41

lapis-redis

Redis integration for Lapis
Lua
22
star
42

luajit-geoip

luajit bindings to maxmind geoip
MoonScript
21
star
43

lua-syntaxhighlight

A code syntax to HTML highlighter using lexers from Textadept
Lua
20
star
44

lapis-exceptions

Exception tracking for Lapis
MoonScript
16
star
45

lapis-systemd

systemd integration for lapis
Lua
16
star
46

lapis-site

The homepage for Lapis
HTML
14
star
47

lua-date

LuaDate 2 modified to work with newer versions of lua/luajit
Lua
14
star
48

mursic

sight reading training tool
MoonScript
14
star
49

moonscript-javascript-compiler

compile moonscript to javascript
MoonScript
14
star
50

moondoc

MoonScript library documentation generator
Lua
13
star
51

lapis-archlinux-docker

Dockerfile for running lapis in archlinux
Dockerfile
13
star
52

moonscript-love

LÖVE game engine with baked in moonscript support
C
13
star
53

lua-uinput

A Lua library for creating a virtual keyboard on Linux with uinput
MoonScript
13
star
54

lua-base58

base58 decode and encode for strings in pure lua
MoonScript
12
star
55

ludum-dare-22

A game built in 48 hours for the Ludum Dare Competition
12
star
56

moonscript-site

CSS
11
star
57

heroku-lapis-example

An example of running Lapis on Heroku with heroku-openresty
Lua
11
star
58

imagesize

Detect size & format of image file
MoonScript
10
star
59

ludum-dare-27

theme: 10 seconds
MoonScript
9
star
60

ludum-dare-25

Make a game in 48 hours!
MoonScript
9
star
61

moonscript-textadept

Textadept support for MoonScript
MoonScript
9
star
62

saltw-bot

irc/twitch bot written in MoonScript
MoonScript
9
star
63

ludum-dare-38

lets make a game "a small world"
MoonScript
8
star
64

lapis-stats

Statsd and Influxdb support for Lua, OpenResty & Lapis
Lua
8
star
65

selfwatch

inspired by selfspy
Go
8
star
66

ludum-dare-24

Let's make a video game!
7
star
67

giflib

gif
MoonScript
7
star
68

garfield

garfield comic viewer 🐱
MoonScript
7
star
69

weeklyloops

loops for http://streak.club/s/134/weekly-loop
Go
7
star
70

snes-renoise-instruments

Various snes samples ripped from spc -> xrni
7
star
71

lapis-spec-screenshot

A busted screenshot handler that takes images of your pages when testing
Lua
7
star
72

moonscrape

web scraper
MoonScript
6
star
73

lessphp-site

the lessphp homepage
PHP
6
star
74

lapis-annotate

Annotate lapis models with their schema from the database
Lua
6
star
75

dullcache

A simple large file cache for sitting in front of storage provider to offload bandwidth
Go
5
star
76

wallrun-js

Trying to get love2d game working in browser using fengari
MoonScript
5
star
77

elng

an interpreted language running on erlang
Erlang
5
star
78

ludum-dare-32

Something butt
MoonScript
4
star
79

lapis-eswidget

A widget base class designed for generating ES modules for bundling JavaScript & more
MoonScript
4
star
80

uglyphp

a templating language for php with emphasis on macros
PHP
4
star
81

fireplace

GTK+ campfire client
Python
4
star
82

album-1

my first album, chiptune
4
star
83

net.leafo.MIDIThing

Control your MIDI modules from Renoise
TeX
4
star
84

gh-actions-openresty

Install OpenResty inside of your GitHub Actions runner
JavaScript
4
star
85

ludum-dare-23

make a game in 48 hours!
4
star
86

lapis-http

HTTP library wrangler for OpenResty & Lua
MoonScript
3
star
87

somestory

lets make a game for real this time....
Lua
3
star
88

ludum-dare-30

Connected worlds
Lua
3
star
89

pixel-react

creating pixelated game interface with html in react
JavaScript
3
star
90

workdad

a chorded keyboard layout and training program
MoonScript
3
star
91

st

my terminal
Objective-C
3
star
92

awesome-config

My awesome configuration
Lua
2
star
93

godot-game-1

GDScript
2
star
94

ludum-dare-41

combine two genres
GDScript
2
star
95

noteshed

a personal wiki for notes
2
star
96

ludum-dare-31

Entire Game on One Screen
MoonScript
2
star
97

ludum-dare-40

Lets make another game
Lua
2
star
98

gslog2pg

Copy Google Cloud storage logs into PostgreSQL
MoonScript
2
star
99

moonparse

MoonScript
2
star
100

gh-actions-test

testing my action to see if it works
Lua
2
star