File: example.html

package info (click to toggle)
lua-orbit 2.2.1%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,964 kB
  • sloc: javascript: 2,216; sql: 78; sh: 32; makefile: 31; xml: 20
file content (847 lines) | stat: -rw-r--r-- 29,471 bytes parent folder | download | duplicates (4)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<title>Orbit</title>
    <link rel="stylesheet" href="http://www.keplerproject.org/doc.css" type="text/css"/>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>

<body>

<div id="container">

<div id="product">

	<div id="product_logo">
        <a href="http://www.keplerproject.org">
		<img alt="Orbit" src="orbit.png"/>
	    </a>
    </div>
	<div id="product_name"><big><strong>Orbit</strong></big></div>
	<div id="product_description">MVC for Lua Web Development</div>
</div> <!-- id="product" -->

<div id="main">
	
<div id="navigation">
<h1>Orbit</h1>
	<ul>

		<li><a href="index.html">Home</a>
			<ul> 
                            
			</ul>
		</li>

		<li><a href="pages.html">Pages</a>
			<ul> 
                            
			</ul>
		</li>

		<li><a href="reference.html">Reference</a>
			<ul> 
                            
			</ul>
		</li>

		<li><strong>Tutorial</strong>
			<ul> 
                            
			</ul>
		</li>

		<li><a href="license.html">License</a>
			<ul> 
                            
			</ul>
		</li>

	</ul>
</div> <!-- id="navigation" -->

<div id="content">


<h2>Orbit Tutorial</h2>

<p>This tutorial shows how to create a simple blog application in Orbit, backed by
a database. It's very simple because it does not include any "admin" pages; you have
to add posts directly to the database (though you can do it through a Lua console, and
this tutorial will show how), but there is an interface for commenting on posts.</p>

<p>The tutorial assumes you have already installed Orbit (preferrably as part of <a href="http://www.keplerproject.org">Kepler</a>,
or via <a href="http://luarocks.org">LuaRocks</a>, and already have a web server that supports WSAPI set up (the Xavante web 
server that comes with Kepler is a good choice).</p>

<p>Complete source code for this blog is in the <code>samples</code> folder of Orbit's distribution.
If you have installed Orbit via Kepler or LuaRocks look inside the <code>rocks</code> folder
of your installation.</p>

<h2>Initialization</h2>

<p>You should create a <code>blog.lua</code> file, which will be the main source file for our application.
The first thing you should put in this file is the code to load Orbit and other libraries you
are going to use in your app:</p>


<pre>
local orbit = require "orbit"
local orcache = require "orbit.cache"
local markdown = require "markdown"
local wsutil = require "wsapi.util"
</pre>


<p>In this example we are going to use Orbit's page cache, and the Markdown parser for marking
up posts.</p>

<p>We will now create the <code>blog</code> application and set it as the global environment for the
rest of the module:</p>


<pre>
local blog = setmetatable(orbit.new(), { __index = _G })
if _VERSION == "Lua 5.2" then
  _ENV = blog
else
  setfenv(1, blog)
end
</pre>


<p><code>orbit.new</code> injects quite a lot of stuff in the <code>blog</code> module's namespace.
The most important of these are the <code>dispatch_get</code>, <code>dispatch_post</code>,
and <code>model</code> methods that let you define the main functionality of the
application. It also defines a <code>mapper</code> variable that Orbit uses to create
the models (Orbit initializes this variable to its default OR mapper). Finally,
it defines default controllers for 404 and 500 HTTP error codes as the
<code>not_found</code> and <code>server_error</code> variables, respectively. Override those if you
want custom pages for your application.</p>

<p>Let's load a configuration script for the blog (a common pattern in applications).
You can get this script from <a href="blog_config.lua">here</a>.</p>


<pre>
wsutil.loadfile("blog_config.lua", blog)()
</pre>


<p>The next few lines load one of LuaSQL's database driver (defined in the configuration),
and sets up Orbit's OR mapper.</p>


<pre>
local luasql = require("luasql." .. database.driver)
local env = luasql[database.driver]()
mapper.conn = env:connect(unpack(database.conn_data))
mapper.driver = database.driver
</pre>


<p>Orbit's mapper needs a database connection to use, and which driver you are
using (currently only "sqlite3" and "mysql" are supported).</p>

<p>You need to initialize the mapper before creating your application's models because
Orbit's mapper hits the database on model creation to get the schema. Speaking of
schema, now is a good time to create your blogs' database. I will assume you are
using SQLite3. Create a <code>blog.db</code> database with the following SQL script:</p>


<pre>
CREATE TABLE blog_post
       ("id" INTEGER PRIMARY KEY NOT NULL,
       "title" VARCHAR(255) DEFAULT NULL,
       "body" TEXT DEFAULT NULL,
       "n_comments" INTEGER DEFAULT NULL,
       "published_at" DATETIME DEFAULT NULL);

CREATE TABLE blog_comment
       ("id" INTEGER PRIMARY KEY NOT NULL,
       "post_id" INTEGER DEFAULT NULL,
       "author" VARCHAR(255) DEFAULT NULL,
       "email" VARCHAR(255) DEFAULT NULL,
       "url" VARCHAR(255) DEFAULT NULL,
       "body" TEXT DEFAULT NULL,
       "created_at" DATETIME DEFAULT NULL);

CREATE TABLE blog_page
       ("id" INTEGER PRIMARY KEY NOT NULL,
       "title" VARCHAR(30) DEFAULT NULL,
       "body" TEXT DEFAULT NULL);
</pre>


<p>Orbit's mapper uses the <code>id</code> field to identify objects in the
database, so you need it for every kind of object you are mapping.</p>

<p>Finally, let's initialize Orbit's page cache before creating our models:</p>


<pre>
local cache = orbit.cache.new(blog, cache_path)
</pre>


<p>The page cache greatly speeds access to any page that you cache, but you need
to be careful and invalidate the cache for a page when any content on that page
changes. We will see how to cache and invalidate pages in the controller
section of this tutorial.</p>

<h2>Creating Models</h2>

<p>Our blog application has three kinds of objects: posts, comments, and
"static" pages (things like an "About" page for the blog, for example). It's no
coincidence that we also have three tables in the database, each table maps
to a kind of object our application handles, and for each kind we will
create a model. We first create a model object for posts:</p>


<pre>
posts = blog:model "post"
</pre>


<p>The parameter for the <code>model</code> method is the name of a table in the database.
The <code>posts</code> object that this method creates represents the collection of
posts, and at the same time is a prototype for all posts (we will see the
implications of that shortly). Orbit's mapper creates a rather functional
object by itself: you can do <code>posts:find(3)</code>, for example, and get the
post with <code>id</code> 3, or <code>posts:find_all("n_comments &lt; ?", { 3, order = "published_at desc" })</code>
and get a list of all posts with less than three comments, ordered by most recent to least.</p>

<p>You can use the predefined <code>find</code> methods for all queries to the database, but it
helps to abstract common queries in your own methods. You can do that by
adding methods to the <code>posts</code> object:</p>


<pre>
function posts:find_recent()
   return self:find_all("published_at is not null",
            { order = "published_at desc",
               count = recent_count })
end
</pre>


<p>The lines above add a <code>find_recent</code> method to the <code>posts</code> object that returns
a list of the most recent published posts (the number is in the configuration script),
ordered from most recent to least. The application is going to use this method
to generate the list of posts in the home page, as well as the "Recent Posts" section
of the blog's sidebar.</p>

<p>Another feature of our blog is going to be archive pages that show all posts of
a certain month and year. We will define a method for that too:</p>


<pre>
function posts:find_by_month_and_year(month, year)
   local s = os.time({ year = year, month = month, day = 1 })
   local e = os.time({ year = year + math.floor(month / 12),
            month = (month % 12) + 1,
            day = 1 })
   return self:find_all("published_at >= ? and published_at < ?",
            { s, e, order = "published_at desc" })
end
</pre>


<p>This is a more complicated method, as we have to convert from a simple month and
year to start and end dates in the standard Lua format. Finally, we will also
define a method that returns all months (and years) that have posts, to later
generate the links for the "Archive" section in the sidebar:</p>


<pre>
function posts:find_months()
   local months = {}
   local previous_month = {}
   local posts = self:find_all("published_at is not null", 
                               { order = "published_at desc" })
   for _, post in ipairs(posts) do
      local date = os.date("*t", post.published_at)
      if previous_month.month ~= date.month or
     previous_month.year ~= date.year then
     previous_month = { month = date.month, year = date.year,
        date_str = os.date("%Y/%m", post.published_at) }
     months[#months + 1] = previous_month
      end
   end
   return months
end
</pre>


<p>This method gets all posts in the database, ordered by date, and iterates over them storing
the each unique pair of month and year in a list.</p>

<p>We can also define methods for individual post objects by defining methods
in the <code>posts</code> object, the only difference is how they are used (you use <code>find_recent</code>
by doing <code>posts:find_recent()</code>, but you will use <code>find_comments</code> by doing <code>p:find_comments()</code>,
where <code>p</code> is a particular post object. We will define a method to retrieve all comments of
a post:</p>


<pre>
function posts:find_comments()
   return comments:find_all_by_post_id{ self.id }
end
</pre>


<p>This method uses a predefined method of the <code>comments</code> object (which we will create
shortly) that gets all comments with field <code>post_id</code> equal to the id of the current
post (<code>self.id</code>). This method establishes a relation between posts and comments;
a future version of Orbit's mapper will let you define these declaratively.</p>

<p>Creating the <code>comments</code> object is simple:</p>


<pre>
comments = blog:model "comment"
</pre>


<p>Let's just add a convenience method for comments that build the comment's link
from the its data:</p>


<pre>
function comments:make_link()
   local author = self.author or strings.anonymous_author
   if self.url and self.url ~= "" then
      return "<a href=\"" .. self.url .. "\">" .. author .. "</a>"
   elseif self.email and self.email ~= "" then
      return "<a href=\"mailto:" .. self.email .. "\">" .. author .. "</a>"
   else
      return author
   end
end
</pre>


<p>The <code>pages</code> object is even simpler, the default functionality provided
by Orbit's mapper is enough, so we just create it with <code>model</code>:</p>


<pre>
pages = blog:model "pages"
</pre>


<p>This concludes the "model" part of our application. We can now move on
to defining the applications' page flow, by defining <em>controllers</em> and
mapping them to URLs.</p>

<h2>Defining Controllers</h2>

<p>Controllers are the interface between the web and your application. With Orbit
you can map the path part of your application's URLs (in http://myserver.com/myapp.ws/foo/bar
the path is /foo/bar, for example) to controllers. In Lua terms, an Orbit
controller is a function that receives a request/response object (usually
called <code>web</code>) plus parameters extracted from the path, and returns text that
is sent to the client (usually HTML, but can be XML, or even an image).</p>

<p>You map paths to controllers with the <code>dispatch_get</code> and <code>dispatch_post</code> methods,
for GET and POST requests, respectively. The first parameter to these methods
is the controller, a Lua function, and all the other parameters are <em>mapping patterns</em>,
written using Lua's string matching syntax, so one controller can answer to multiple mappings.</p>

<p>Below is the controller for the main page of the blog:</p>


<pre>
function index(web)
   local ps = posts:find_recent()
   local ms = posts:find_months()
   local pgs = pgs or pages:find_all()
   return render_index(web, { posts = ps, months = ms,
              recent = ps, pages = pgs })
end

blog:dispatch_get(cache(index), "/", "/index") 
</pre>


<p>The last line sets up the mapping between the <code>index</code> function and the root
of the application. The call to <code>cache</code> sets up page caching for this controller,
using the cache we created earlier (this is another common Lua idiom, functions
as decorators).</p>

<p>The <code>index</code> controller shows all recent posts, and is pretty straightforward. It
just fetches the required model data from the database, then calls an auxiliary
function (called a <em>view</em> in MVC terminology) to render the actual HTML code.</p>

<p>Another important controller is the one that shows single posts:</p>


<pre>
function view_post(web, post_id, comment_missing)
   local post = posts:find(tonumber(post_id))
   if post then
      local recent = posts:find_recent()
      local pgs = pages:find_all()
      post.comments = post:find_comments()
      local months = posts:find_months()
      return render_post(web, { post = post, months = months,
                recent = recent, pages = pgs,
                comment_missing = comment_missing })
   else
      return not_found(web)
   end
end

blog:dispatch_get(cache(view_post), "/post/(%d+)")
</pre>


<p>Here we map all paths like /post/53 to the <code>view_post</code> controller. The pattern
captures the number, and this is passed along to the controller by Orbit. For
/post/53, the controller receives the string "53" as <code>post_id</code> and uses this
to fetch the corresponding post. Again, HTML rendering is factored out to
another function, and this controller is cached.</p>

<p>If no post with that id is found then the default controller for missing
pages gets called, <code>blog.not_found</code> (<code>orbit.app</code> put it in the <code>blog</code> namespace).
Orbit also calls this controller is it does not find a valid match for the
path. Another default controller is <code>server_error</code>, called when any unprotected
error happens in controller/view code.</p>

<p>Archives and pages are similar in structure:</p>


<pre>
function view_archive(web, year, month)
   local ps = posts:find_by_month_and_year(tonumber(month),
                       tonumber(year))
   local months = posts:find_months()
   local recent = posts:find_recent()
   local pgs = pages:find_all()
   return render_index(web, { posts = ps, months = months,
              recent = recent, pages = pgs })
end

blog:dispatch_get(cache(view_archive), "/archive/(%d%d%d%d)/(%d%d)")

function view_page(web, page_id)
   local page = pages:find(tonumber(page_id))
   if page then
      local recent = posts:find_recent()
      local months = posts:find_months()
      local pgs = pages:find_all()
      return render_page(web, { page = page, months = months,
             recent = recent, pages = pgs })
   else
      not_found(web)
   end
end

blog:dispatch_get(cache(view_page), "/page/(%d+)")
</pre>


<p>The archives use the same layout as the index, so they reuse its HTML
generator. Archives also extract two parameters from the path, the month and
the year, so paths are like /archive/2008/05.</p>

<p>Finally, you can also set up Orbit to serve static files with the <code>dispatch_static</code>
convenience method:</p>


<pre>
blog:dispatch_static("/head%.jpg", "/style%.css")
</pre>


<p>These are also patterns, so the dots are escaped. You can set up a whole folder in
your application as static with <code>blog:dispatch_static("/templates/.+")</code>. Orbit always
looks for the files in your application's folder. Of course you are free to let
your application only handle dynamic content and let your web server serve static
content; <code>dispatch_static</code> is just a convenience to have "zero-configuration" applications.</p>

<p>There is one controller left, for adding comments. This one will answer to POST
instead of GET:</p>


<pre>
function add_comment(web, post_id)
   local input = web.input
   if string.find(input.comment, "^%s*$") then
      return view_post(web, post_id, true)
   else
      local comment = comments:new()
      comment.post_id = tonumber(post_id)
      comment.body = markdown(input.comment)
      if not string.find(input.author, "^%s*$") then
     comment.author = input.author
      end
      if not string.find(input.email, "^%s*$") then
     comment.email = input.email
      end
      if not string.find(input.url, "^%s*$") then
     comment.url = input.url
      end
      comment:save()
      local post = posts:find(tonumber(post_id))
      post.n_comments = (post.n_comments or 0) + 1
      post:save()
      cache:invalidate("/")
      cache:invalidate("/post/" .. post_id)
      cache:invalidate("/archive/" .. os.date("%Y/%m", post.published_at))
      return web:redirect(web:link("/post/" .. post_id))
   end
end

blog:dispatch_post(add_comment, "/post/(%d+)/addcomment")
</pre>


<p>The <code>add_comment</code> controller first validates the input, delegating
to <code>view_post</code> if the comment field is empty (which will show an error
message in the page). You access POST parameters via the <code>web.input</code> table,
which is conveniently aliased to an <code>input</code> local variable.</p>

<p>The controller creates a new comment object and fills it with data, then
saves it to the database. It also updates the post object to increase the
number of comments the post has by one, and also saves it. It then proceeds
to invalidate (in the cache) all pages that may show this information: the index, the post's page,
and the archives for this particular post. Finally, it redirects to the post's page,
which will show the new comment. This is a common idiom in web programming
called POST-REDIRECT-GET, where every POST is followed by a redirect to a GET.
This avoids double posting in case the user hits reload.</p>

<p>The only thing left now is the HTML generation itself. This is the topic of the next section.</p>

<h2>Views: Generating HTML</h2>

<p>Views are the last component of the MVC triad. For Orbit views are just simple functions that
generate content (usually HTML), and are strictly optional, meaning you can return content
directly from the controller. But it's still good programming practice to separate controllers
and views.</p>

<p>How you generate content is up to you: concatenate Lua strings, use <code>table.concat</code>, use
a third-party template library... Orbit provides programmatic HTML/XML generation
through <code>orbit.htmlify</code>, but you are free to use any method you want. In this tutorial
we will stick with programmatic generation, though, as the other methods (straight
strings, <a href="http://cosmo.luaforge.net">Cosmo</a>, etc.) are thoroughly documented elsewhere.</p>

<p>When you htmlify a function, Orbit changes the function's environment to let you generate
HTML by calling the tags as functions. It's better to show how it works than to explain, so
here is the basic view of the blog application, <code>layout</code>:</p>


<pre>
function layout(web, args, inner_html)
   return html{
      head{
     title(blog_title),
     meta{ ["http-equiv"] = "Content-Type",
        content = "text/html; charset=utf-8" },
     link{ rel = 'stylesheet', type = 'text/css', 
        href = web:static_link('/style.css'), media = 'screen' }
      },
      body{
     div{ id = "container",
        div{ id = "header", title = "sitename" },
        div{ id = "mainnav",
           _menu(web, args)
        }, 
            div{ id = "menu",
           _sidebar(web, args)
        },  
        div{ id = "contents", inner_html },
        div{ id = "footer", copyright_notice }
     }
      }
   } 
end
</pre>


<p>This view is a decorator for other views, and generates the boilerplate for each
page in the blog (header, footer, sidebar). You can see the HTML-generating functions
througout the code, such as <code>title</code>, <code>html</code>, <code>head</code>, <code>div</code>. Each takes either a string
or a table, and generates the corresponding HTML. If you pass a table, the array part
is concatenated and used as the content, while the hash part os used as HTML attributes
for that tag. A tag with no content generates a self-closing tag (<code>meta</code> and <code>link</code> in
the code above).</p>

<p>Of note in the code above are the calls to <code>web:static_link</code> and to the <code>_menu</code> and
<code>_sidebar</code> functions. The <code>static_link</code> method generates a link to a static resource
of the application, stripping out the SCRIPT_NAME from the URL (for example,
if the URL is http://myserver.com/myblog/blog.ws/index it will return /myblog/style.css
as the link).</p>

<p>The <code>_menu</code> and <code>_sidebar</code> functions are just helper views to generate the blog's menubar
and sidebar:</p>


<pre>
function _menu(web, args)
   local res = { li(a{ href= web:link("/"), strings.home_page_name }) }
   for _, page in pairs(args.pages) do
      res[#res + 1] = li(a{ href = web:link("/page/" .. page.id), page.title })
   end
   return ul(res)
end

function _sidebar(web, args)
   return {
      h3(strings.about_title),
      ul(li(about_blurb)),
      h3(strings.last_posts),
      _recent(web, args),
      h3(strings.blogroll_title),
      _blogroll(web, blogroll),
      h3(strings.archive_title),
      _archives(web, args)
   }
end
</pre>


<p>Here you see a mixture of standard Lua idioms (filling a table and passing it
to a concatenation function) and Orbit's programmatic HTML. They also use
the <code>web:link</code> method, which generates intra-application links. The <code>sidebar</code>
function uses a few more convenience functions, for better factoring:</p>


<pre>
function _blogroll(web, blogroll)
   local res = {}
   for _, blog_link in ipairs(blogroll) do
      res[#res + 1] = li(a{ href=blog_link[1], blog_link[2] })
   end
   return ul(res)
end

function _recent(web, args)
   local res = {}
   for _, post in ipairs(args.recent) do
      res[#res + 1] = li(a{ href=web:link("/post/" .. post.id), post.title })
   end
   return ul(res)
end

function _archives(web, args)
   local res = {}
   for _, month in ipairs(args.months) do
      res[#res + 1] = li(a{ href=web:link("/archive/" .. month.date_str), 
                blog.month(month) })
   end
   return ul(res)
end
</pre>


<p>Notice how these functions do not call anything in the model, just using
whichever data was passed by them (all the way from the controller).</p>

<p>We can now get to the main view functions. Let's start with the easiest,
and smallest, one, to render pages:</p>


<pre>
function render_page(web, args)
   return layout(web, args, div.blogentry(markdown(args.page.body)))
end
</pre>


<p>This is a straightforward call to <code>layout</code>, passing the body
of the page inside a <code>div</code>. The only thing of note
is the <code>div.blogentry</code> syntax, which generates a <code>div</code> with
a <code>class</code> attribute equal to "blogentry", instead of a straight
<code>div</code>.</p>

<p>Moving on, we will now write the view for index pages (and archive
pages):</p>


<pre>
function render_index(web, args)
   if #args.posts == 0 then
      return layout(web, args, p(strings.no_posts))
   else
      local res = {}
      local cur_time
      for _, post in pairs(args.posts) do
     local str_time = date(post.published_at)
     if cur_time ~= str_time then
        cur_time = str_time
        res[#res + 1] = h2(str_time)
     end
     res[#res + 1] = h3(post.title)
     res[#res + 1] = _post(web, post)
      end
      return layout(web, args, div.blogentry(res))
   end
end
</pre>


<p>Again we mix Lua with programmatic generation, and factor part
of the output (the HTML for the body of the posts themselves) to another function
(we will be able to reuse this function for the single-post view). The
only unusual piece of logic is to implement fancier dates, the code
only prints a date when it changes, so several posts made in the same
day appear under the same date.</p>

<p>The <code>_post</code> helper is pretty straightforward:</p>


<pre>
function _post(web, post)
   return {
      markdown(post.body),
      p.posted{ 
     strings.published_at .. " " .. 
        os.date("%H:%M", post.published_at), " | ",
     a{ href = web:link("/post/" .. post.id .. "#comments"), strings.comments ..
        " (" .. (post.n_comments or "0") .. ")" }
      }
   }
end
</pre>


<p>Now we can finally move to the piece-de-resistance, the view that renders
single posts, along with their comments, and the "post a comment" form:</p>


<pre>
function render_post(web, args)
   local res = { 
      h2(span{ style="position: relative; float:left", args.post.title }
     .. "&nbsp;"),
      h3(date(args.post.published_at)),
      _post(web, args.post)
   }
   res[#res + 1] = a{ name = "comments" }
   if #args.post.comments > 0 then
      res[#res + 1] = h2(strings.comments)
      for _, comment in pairs(args.post.comments) do
     res[#res + 1 ] = _comment(web, comment)
      end
   end
   res[#res + 1] = h2(strings.new_comment)
   local err_msg = ""
   if args.comment_missing then
      err_msg = span{ style="color: red", strings.no_comment }
   end
   res[#res + 1] = form{
      method = "post",
      action = web:link("/post/" .. args.post.id .. "/addcomment"),
      p{ strings.form_name, br(), input{ type="text", name="author",
     value = web.input.author },
         br(), br(),
         strings.form_email, br(), input{ type="text", name="email",
     value = web.input.email },
         br(), br(),
         strings.form_url, br(), input{ type="text", name="url",
     value = web.input.url },
         br(), br(),
         strings.comments .. ":", br(), err_msg,
         textarea{ name="comment", rows="10", cols="60", web.input.comment },
     br(),
         em(" *" .. strings.italics .. "* "),
         strong(" **" .. strings.bold .. "** "), 
         " [" .. a{ href="/url", strings.link } .. "](http://url) ",
         br(), br(),
         input.button{ type="submit", value=strings.send }
      }
   }
   return layout(web, args, div.blogentry(res))
end
</pre>


<p>This is a lot of code to digest at once, so let's go piece by piece. The first few lines
generate the body of the post, using the <code>_post</code> helper. Then we have the list of comments,
again with the body of each comment generated by a helper, <code>_comment</code>. In the middle we
have an error message that is generated if the user tried to post an empty comment, and
then the "add a comment" form. A form needs a lot of HTML, so there's quite a lot of
code, but it should be self-explanatory and is pretty basic HTML (making it pretty is
the responsibility of the style sheet).</p>

<p>The <code>_comment</code> helper is pretty simple:</p>


<pre>
function _comment(web, comment)
   return { p(comment.body),
      p.posted{
     strings.written_by .. " " .. comment:make_link(),
     " " .. strings.on_date .. " " ..
        time(comment.created_at) 
      }
   }
end
</pre>


<p>Finally, we need to set all of these view functions up for programmatic HTML generation:</p>


<pre>
orbit.htmlify(blog, "layout", "_.+", "render_.+")
</pre>


<p>The <code>orbit.htmlify</code> function takes a table and a list of patterns, and sets all
functions in that table with names that match one of the patterns up for
HTML generation. Here we set the <code>layout</code> function, all the <code>render_</code> functions,
and all the helpers (the functions starting with <code>_</code>).</p>

<p>We end the file by returning the module:</p>


<pre>
return blog
</pre>



<h2>Deployment</h2>

<p>For this part of the tutorial it is better if you go to the <code>samples/blog</code> folder
of Orbit's distribution (again, look inside the <code>rocks</code> folder if you installed
with Kepler or LuaRocks). An Orbit application is a WSAPI application, so
deployment is very easy, you can just copy all the application's files (<code>blog.lua</code>,
<code>blog_config.lua</code>, <code>blog.db</code>, <code>head.jpg</code>, and <code>style.css</code>) to a folder in your
web server's docroot (if you installed Kepler, to a folder inside <code>kepler/htdocs</code>),
and create a launcher script in this folder. The launcher script is simple (call 
it <code>blog.ws</code>):</p>


<pre>
#!/usr/bin/env wsapi.cgi
return require "blog"
</pre>


<p>Depending on your configuration, you might need to install the <code>luasql-sqlite3</code> and
<code>markdown</code> rocks before running the application. Now just start Xavante, and
point your browser to blog.ws, and you should see the index page of the blog. If you
created a blog.db from scratch you are not going to see any posts, though. The blog
application in `samples/blog' includes a blog.db filled with random posts and comments.</p>




</div> <!-- id="content" -->

</div> <!-- id="main" -->

<div id="about">
	<p><a href="http://validator.w3.org/check?uri=referer">Valid XHTML 1.0!</a></p>
</div> <!-- id="about" -->

</div> <!-- id="container" -->

</body>
</html>