" />
开发者

lift:testCond - how it works?

i discovered this in lift examples:

<lift:TestCond.loggedout>
  <lift:embed what="/templates/_login_panel"/>
</lift:TestCond.loggedout>
How do I tweak this lift开发者_运维技巧 tag if I want to test any other condition? Is this some kind of <c:if/> tag in JSP or the idea is somewhere else?


lift:TestCond refers to the snippet object TestCond which only provides the loggedIn and loggedOut methods. There is no general <c:if/> available in Lift because it would blur the boundaries between code and markup.

If you want different behaviour, you’ll need to implement such tests yourself and make them explicit in your code. But its really simple. By looking at the source code, you can get an idea of how to customise this to your needs.

The code for loggedIn is as simple as

def loggedIn(xhtml: NodeSeq): NodeSeq =  
  if (S.loggedIn_?) xhtml else NodeSeq.Empty  

So, for example, you could implement a different behaviour which allows for

<lift:HasRole.administrator />

or, more advanced

<lift:HasRole.any type="administrator manager" />

or something similar. But this really depends on your use case, so I think it’s not possible to make this generic in Lift.


As a side-note I have written a small utility which performs this task for me:

object SnippetUtil {
  def testCond[T](value: Box[T], in: NodeSeq, f: T => Boolean): NodeSeq =
    value match {
      case Full(v) if f(v) => in
      case _ => NodeSeq.Empty
    }
}

Then you can use it like the following in a DispatchSnippet for instance:

object SearchSnippet extends DispatchSnippet {
  def dispatch = {
    case "hasParameter" => testCond[String](S.param("s"), _, _.nonEmpty)
    // ...
  }
}

You can decide whether or not you want to write testCond[Type](...) or testCond(...). In the second case you will have to specify the type of the function. E.g. testCond(S.param("s"), _, (_: String).nonEmpty).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜