lua-users home
lua-l archive

Re: how to loop in lua page(not the php way) ?

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


Mark Edgar wrote:
On 3/15/07, Tomas Guisasola Gorham <tomas@tecgraf.puc-rio.br> wrote:
<?lua
for i=1,10 do
?>
<p><%= tostring(i) %></p>
<?lua
end
?>
I can't stand all the <?lua ?> cruft. Instead, I use slslpp:
http://lua-users.org/wiki/SlightlyLessSimpleLuaPreprocessor
# for i = 1,10 do
<p>$(i)</p>
# end
Of course, this doesn't answer the OP's question. I think the answer
to that question is: if you want KidLanguage, you know where to find
it. ;)
Well... I actually have implemented my template library inspired on Kid.
I like Lua, like Kid but don't quite like XML, so...
-- sometemplate.lua
html{
 head{
 title{ "Hello, world" };
 link{ rel = "stylesheet", src = "style.css" };
 };
 body{
 div{ id = "header"; "Welcome to ${sitetitle}!" };
 div{ _if = "session.logged"; id = "menu"; class = "sidemenu";
 ul{
 li{ _for = "i, section in ipairs( session.sections )";
 a{ href = "${section.href}", "${section.title}" };
 };
 };
 };
 };
};
And it compiles (on the fly) another Lua script (for performance and debugging reasons):
out("<html>")
out("<head>")
out("<title>")
out("Hello, world")
...
out("<div id=\"header\">")
out("Welcome to ")
out(sanitize(sitetitle))
out("!")
if (session.logged) then
 out("<div id=\"menu\" class=\"sidemenu\">")
 out("<ul>")
 for i, section in ipairs( session.sections ) do
 out("<li>")
 out("<a href=\"")
 out(section.href)
 out("\">")
 out(sanitize(section.title))
 out("</a>")
 out("</li>")
 end
 out("</ul>")
 out("</div>")
end
...
out("</html>")
Of course, in real-world, I optimize those outputs to something like:
out("<html><head><title>Hello, World</title> ... <div id=\"header\">Welcome to ", sanitize(sitetile), "!")
if (session.logged) then
 out("<div id=\"menu\" class=\"sidemenu\"><ul>")
 for i, section in ipairs( session.sections ) do
out("<li><a href=\"",section.href,"\">",sanitize(section.title),"</a></li>")
 end
 out("</ul></div>")
end
out("...</body></html>")
I must say it is quite comfortable and fast. The only drawback is that debug can get a bit boring, because the line numbers differs (the one in which the expression was declared and the one which lies on the compiled code)
--rb

AltStyle によって変換されたページ (->オリジナル) /