UrlRewriting

From Lift

Jump to: navigation, search

URL rewriting in lift is done by using the LiftRules.addRewriteBefore method in Boot.scala

In this example, lets assume we want a pretty url like http://example.org/product/show/my-lovely-product where "my-lovely-product" was some kind of key from a database. To get this to work we would need to use rules a bit like the following:

    LiftRules.addRewriteBefore {
      case RewriteRequest(ParsePath("product" :: "show" :: product :: Nil, _,_), _, _) =>
           RewriteResponse(List("product_display"), Map("product" -> product))
    } 

Lets break that down:

case RewriteRequest(ParsePath("product" :: "show" :: product :: Nil, _,_), _, _)

This will match a url or /product/show/<product> and nothing else (e.g /product/show will not be matched)

RewriteResponse(List("product_display"), Map("product" -> product))

The request will then be handed off internally to the product_display file within your webapp directory. The Map() then binds the value of product in the ParsePath method to a value we can call in our snippet with S.param("product") and use to do whatever we like as you would with any other snippet.

It is important that any URL you want to rewrite is allowed for in your sitemap (if you have one). If not, you will still get a 404 even if the rewrite is correct


To quote DPP from a conversation had on the google group, he gives some great advice for Url rewriting in "lift":

This [rewriting] is all done with Scala's pattern matching.

"foo" :: something 

And

"foo" :: something :: _ 

And

"foo" :: something :: Nil 

Are all different.

In the first example, something is a List[String] containing all the items after "foo" so "/foo" will match this pattern and something will be Nil. "/foo/bar/baz" will also match and something will be List("bar", "baz")

The second line matches "/foo/bar" where something = "bar" and "/foo/bar/baz" where something is still "bar". The third line matches "/foo/bar" where something = "bar" but will not match "/foo" or "/foo/bar/baz"

You can read more about Pattern matching at Scala Lang: Pattern Matching and Scala Lang: Extractors

DPP's comments were from this thread which may also be of use.

Personal tools