4

I need to be able to declare variables and after some markup later I need to reference them. In order to accomplish this, this is simplified version of my scala template:

@(map1: 
java.util.LinkedHashMap[String,java.util.LinkedHashMap[String,Object]]) 
@import scala.collection.JavaConversions._ 
@import play.Logger 
@for( (key,value) <- map1) { 
    <div> 
    @{ 
       val rmap = Foo.someMethod(value) 
       val baz = rmap.getOrElse("baz", null) 
    <table border="0"  cellpadding="0" cellspacing="0"  > 
    <tbody> 
    <tr> 
      <td rowspan="3"> 
        <div class="bar"> 
          @baz 
        </div> 
      </td> 
    </tr> 
    </tbody> 
  </table> 
  } 
  </div> 
} 

Is above valid scala template and if not how can I declare baz and reference it later in the markup? I am using 1.2.2RC2 and scala 0.9.1

1
  • Not an answer but a tip: check in tmp/, the scala code generated from your template lives there (in a subdirectory - I don't have a Scala project handy to check). Often helpful to see what exactly happens under the hood :) Commented Jul 6, 2011 at 9:45

2 Answers 2

8

I was curious so did some digging. See https://groups.google.com/forum/#!topic/play-framework/Mo8hl5I0tBQ - there is no way at the moment, but an interesting work-around is shown. Define utils/Let.scala:

package utils
Object Let {
    def let[A,B](a:A)(f:A=>B):B = f(a)
}

and then

@import utils.Let._

@let(2+3){ answer =>
   @answer <hr> @answer
}

It's a very functional way of handling it, but then, what'd you expect in Scala :)

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe it is newer than this answer, but there's now a "defining" function in Play which does exactly this.
3

You can just use a for comprehension:

@for( (key,value) <- map1;
     rmap = Foo.someMethod(value);
     baz = rmap.getOrElse("baz", null)
) { 
<div> 
  <table border="0"  cellpadding="0" cellspacing="0"  > 
    <tbody> 
      <tr> 
        <td rowspan="3"> 
          <div class="bar"> 
            @baz 
          </div> 
        </td> 
      </tr> 
    </tbody> 
  </table> 
</div> 
} 

... and if you don't have anything you need to loop over, you can just say @for(i <- List(1); <declare variables>){<html here>}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.