nrk (owner)

Revisions

gist: 216771 Download_button fork
public
Description:
Mercury's greetings example ported to mustache.
Public Clone URL: git://gist.github.com/216771.git
Embed All Files: show embed
greetings-mustache.lua #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
-- Here is mercury's greetings example ported to mustache.
-- Note that support for partial templates is still missing.
 
require 'luarocks.require'
require 'mercury'
require 'mustache'
 
module('greetings', package.seeall, mercury.application)
 
local templates = {
    index = [[
<html>
<head>
<title>{{page_title}}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Welcome to the first Mercury application ever built!<br /><br />
<form action="./say_hi/" method="post">
<fieldset>
<legend>Please fill in your name and choose your preferred language</legend>
<input type="text" id="name" name="name" /><br/>
English<input type="radio" name="lang" value="en"/><br/>
Italian<input type="radio" name="lang" value="it"/><br/>
Japanese<input type="radio" name="lang" value="ja"/><br/>
</fieldset>
<input type="submit" value="Go on...">
</form>
</body>
</html>]],
 
    greetings = [[
<html>
<head>
<title>{{page_title}}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
{{#has_name}}
{{localized_greeting}}
{{#is_post}}
<br/><br/>If you do not like POST-based greetings, then
<a href="{{generate_get_link}}">you can try this!</a>
{{/is_post}}
{{/has_name}}
{{#has_no_name}}
Sorry but I do not believe you, you can not have no name ;-)
Please <a href="javascript:history.go(-1)">try again</a>.
{{/has_no_name}}
</body>
</html>]],
}
 
local view = {
    page_title = 'Sinatra in Lua? Sure, it is called "Mercury"!',
 
    languages = {
        en = 'Hi %s, how are you?',
        it = 'Ciao %s, come stai?',
        ja = '今日は%sさん、お元気ですか。'
    },
 
    is_post = function() return request.method == 'POST' end,
    has_no_name = function() return params.name == '' or not params.name end,
    has_name = function() return not has_no_name() end,
 
    get_language_id = function() return params.lang or 'en' end,
    get_base_greeting = function() return languages[get_language_id()] end,
 
    localized_greeting = function()
        return (get_base_greeting()):format(params.name)
    end,
 
    generate_get_link = function()
        return string.format('../say_hi/%s/%s/', get_language_id(), params.name)
    end,
}
 
 
get('/', function()
    t.mustache(templates.index, view)
end)
 
post('/say_hi/', function()
    t.mustache(templates.greetings, view)
end)
 
get('/say_hi/:lang/:name/', function()
    t.mustache(templates.greetings, view)
end)