Search code examples
scalalift

Accessing bind-at values from a snippet in Lift


I have a template that looks like this:

<lift:surround name="default" at="page-content">
  <lift:bind-at name="page-title">Home</lift:bind-at>
  ...
</lift:surround>

The default template looks like this:

<html>
 <head>
  <title>Title Prefix | </title>
 </head>
 <body>
    <h1><lift:bind name="page-title" /></h1>
    <div id="page-content">
      <lift:bind name="page-content" />
    </div>
 </body>
</html>

I want to use a snippet to replace the <title> content with a string that combines "Title Prefix" and the value of <lift:bind-at name="page-title"> (ie: "Home"). I want to contine to use that same value inside the <h1> in the <body>

How can I access a bind-at value from within a snippet that's used in the surrounding template?


Solution

  • I don't believe you can do what you are looking to do with bind-at directives, or at least, I haven't found a way. You should be able to use a snippet to accomplish something similar though.

    For example, if you are using SiteMap, the following should be roughly equivalent.

    class TitleSnippet {
      //Store the value in a requestVar
      private var titleVar:String = ""
    
      def first = {
        //Retrieve the title for the current Loc as defined in the Sitemap
        val locTitle = for (request <- S.request;
          loc <- request.location) yield loc.title
    
        //Retrieve the text portion of the tag, and append it to the sitemap title. 
        //If no sitemap title exists, just display the text
        "* *" #> { ns => 
          val myTitle = locTitle.map{ t => 
            "%s | %s".format(ns.text, t) 
          } openOr ns.text 
          titleVar = myTitle
          Text(myTitle)
        }
      }
    
      def title = {
        "* *" #> titleVar
      }
    }
    

    Then, in your template, all you'd have to do is say:

    <title data-lift="TitleSnippet.first">Home</title>
    

    So, if we had a page defined like this in the sitemap:

    Menu("Sub Page 1") / "subpage"
    

    If everything worked, you should see a title like: <title>Home | Sub Page 1</title> and if you need it elsewhere on the page, all you would have to do is: <h1 data-lift="TitleSnippet.title"></h1>.

    If you need access from other snippets, you can also break out titleVar into a companion object and use a RequestVar.