Play! framework: define a variable in template? [duplicate]

大憨熊 提交于 2019-11-27 01:20:32

问题


This question already has an answer here:

  • Declare variable in a Play2 scala template 8 answers

I'm passing to a template an Event object and what I need to do is checking @event.getSeverity value. if the value is positive, I want to color a specific <div> in green. if the value is negative I want to color a specific <div> in red.

I couldn't find a way to define a variable. is it possible? it should be I think.
anyhow, what's the simplest way accomplishing this?

thanks


回答1:


As stated in the Play documentation you can use the @defining helper.

@defining(if (event.getSeverity > 0) "green" else "red") { color =>
    <div style="background-color: @color">foo</div>
}

Or you can use a reusable block

@severityColor(event: Event) = @{
    if (event.getSeverity > 0) "green" else "red"
}

<div style="background-color: @severityColor(event)">foo</div>



回答2:


try this in scala template

@import java.math.BigInteger; var i=1; var k=1  

and for string

@import java.lang.String; val name="template"

in question aspect

@import java.lang.String; var color="red"
@if(event.getSeverity>0){
@{color="green"}
}
<div style="background-color: @color">foo</div>



回答3:


Another variant. Works fine if declared after import section. Otherwise may cause some errors ("value not found")

@import play.i18n.Messages
@import models.Customers

@customers = @{Customers.allAccepted()}

...

@if(customers.size()>0) {
    <ul>
        @for(customer <- customers) {
            <li>
                <a href="/filters/customer/@customer.id">@customer.name</a>
            </li>
        } 
    </ul>
}



回答4:


"for" comprehensions can be also useful some times:
@for(id <- products.keys; product = products(id); author = product.author.getOrElse("N/A")) {... @product.name ... @author



来源:https://stackoverflow.com/questions/13056747/play-framework-define-a-variable-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!