简体   繁体   中英

How to create a constant using play framework 2.0 views

Hi I'm using the play framework in Java

I need to create a constant in a view and use it in a loop.

To illustrate this will be the code in a view

@for(i <- 1 to 7){
@if(i>=wd) {   //The constant wd is defined outside but in  
    <td>@cur++</td>
}else {
    <td></td>
    }
}   

(I have to use wd many times and I think its a little ugly to pass it from the controller). Is there no way to just create a constant?

I looked at

@defining(user.getFirstName() + " " + user.getLastName()) { fullName =>
  <div>Hello @fullName</div>
}

but this doesn't seem to help Thanks

The defining block should be exactly what you need for this:

If your constant is limited to the template you simply wrap your whole template in the defining block:

@defining( 1 ){ wd =>

    @for(i <- 1 to 7){
        @if(i>=wd) {  
            <td>@cur++</td>
        } else {
            <td></td>
        }
    } 
}

You're also not limited to Integer s in there, you can define Strings, Lists, ... in there aswell.

If you want to use that constant in multiple templates, consider putting it in an Enum and get the value from the enum in the defining block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM