Search code examples
scalareflectionlift

How Do I Call Snippets From Different Packages In Lift?


I am trying to call one of 2 snippet methods with the same name and same class, but these snippets are located in different packages. Here's the example code:

Snippet 1:

package v1.site.snippet

class TestSnippet {

  def test = { println("printed from v1") }

}

Snippet 2:

package v2.site.snippet

class TestSnippet {

  def test = { println("printed from v2") }

}

index.html:

<div class="lift:TestSnippet.test"></div>

So how do I tell index.html which TestSnippet.test to call? Both packages have been added in my Boot.scala.


Solution

  • One option:

    LiftRules.snippetDispatch.append {
      case "V1TestSnippet" => new v1.site.snippet.TestSnippet
      case "V2TestSnippet" => new v2.site.snippet.TestSnippet
    }
    

    Your snippets must then inherit DispatchSnippet and define def dispatch = { case "test" => test _ } etc. You then invoke the snippets from the template as V1TestSnippet or V2TestSnippet.

    Alternatively, something like

    LiftRules.snippets.append {
      case "V1TestSnippet"::"test"::Nil => (new v1.site.snippet.TestSnippet).test _
      case "V2TestSnippet"::"test"::Nil => (new v2.site.snippet.TestSnippet).test _
    }
    

    I believe the List is the snippet name in the template split on dots.