HowTo decorate your markup with dynamic attributes
From Lift
Hi,
Noodling around with Lift made me think of how do we use dynamic attributes. I mean lift is great for building dynamic markup sequences but what if we want just to put dynamic attributes? For instance under certain conditions we would like to set the dir="rtl" for the html tag or to other specific tags.
If you remember with JSTL/JSF one could write something like:
<html dir="${MyBean.direction}"> // well this would work for JSF 1.2 not 1.(x < 2)
</html>
But this aproach is not very good and it's pretty limited to JavaBeans getters ... JST/JS EL even Unified EL is cumbersome(IMO).
So the way I was doing this was:
1. In my default template I wrapped the html tag with a wrapper snippet like:
<lift:Hello.wrap> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>Hello Darwin</title> <script id="jquery.js" src="/classpath/toserve/jquery.js" type="text/javascript"></script> </head> <body> <div style="border-bottom: 1px dotted blue"> </div> <lift:bind name="content" /> <div style="border-bottom: 1px dotted blue"> </div> <lift:error_report /> </body> </html> </lift:Hello.wrap>
.. the content does not really matter
2. Defined the snippet like:
def wrap(xhtml: Group): NodeSeq = {
xhtml map (v => v match {
case (<html>{_*}</html>) => Elem(v.prefix, v.label, (v attributes) append ("dir" -> "rtl"), v.scope, v.child:_*)
case _ => v
})
}
3. That's pretty much it. In terms of the performance measuring the wrap roundtrip most of the times I got ZERO ms but of course this would slightly differ for larger markups. But I don't think this is a concern though.
David Bernard also mentioned "a not available lift feature : PageTransformer, but you could request it for future ;) ". But I guess It would be pretty much the same thing as the above approach except we don't have to wrap our markup with a snippet. I like David's suggestion and hopefully David P. likes it too. There is a good chance though that David P. to suggest a simpler way ;)
David P. just pointed this out:
<div lift:snippet="MyDivThing:calcDir"> ... </div>
class MyDivThing {
def calcDir= new UnprefixedAttribute("dir", "rtl", Null)
}
Cool stuff !
P.S.
Also please see http://groups.google.com/group/liftweb/browse_thread/thread/c7fe7b4b381446b5 for other alternatives discussed.
Br's,
Marius

