Declare variable in a Play2 scala template

前端 未结 8 1592
谎友^
谎友^ 2020-11-27 17:33

How do you declare and initialize a variable to be used locally in a Play2 Scala template?

I have this:

@var title : String = \"Home\"
8条回答
  •  盖世英雄少女心
    2020-11-27 18:12

    There is one obvious solution which looks quite clean and may be preferred sometimes: define a scope around the template, define your variable inside of it, and let the scope produce the html code you need, like this:

    @{
      val title = "Home"
    
      

    Welcome on {title}

    }

    This has some drawbacks:

    • you are generating your html as Scala NodeSeq this way, which may be limiting sometimes
    • there is a performance issue with this solution: the code inside of @{ seems to be compiled runtime, because the Scala code generated for the page loooks like this (some usual Twirl stuff deleted):

    The generated code:

    ...    
    
    Seq[Any](format.raw/*1.1*/("""
    
        
            
            Basic Twirl
        
        
    
            """),_display_(/*9.10*/{
                val title = "Home"
    
                    

    Welcome on {title}

    }),format.raw/*15.10*/(""" """),format.raw/*17.5*/(""" """)) } } } ...

提交回复
热议问题