Scala template set variable

2019-02-27 09:16发布

问题:

I am new to Scala (Scala templates in Play 2 framework), I want to do the following: Pass a parameter isEdit and depending on this parameter, define a value, Pseudocode:

variable myTitle;

if(isEdit)
    myTitle="edit question";
else
    myTitle="create question";

How to formulate this in a Scala Template in Play 2.0? Passing isEdit is not the problem, only creating the new variable myTitle. Thanks :-)

回答1:

First of all, look over the Playframework documentation as there's a lot of good info on templates there. http://www.playframework.org/documentation/2.0.4/ScalaTemplates

Now, if you need to reuse the value throughout the template then you can declare it at the top of your template (probably after any @imports):

@myTitle = @{ if(isEdit) "edit question" else "create question" }

If you only need it in one spot then you really just need the if-else block:

<h1>
  @if(isEdit) {
    edit question
  } else {
    create question
  }
</h1>


回答2:

You cannot use variables in that way in a view template (correct me if im wrong). I would use javascript do to what you want to do, ie pass isEdit to some javascript function and from that set the title.



回答3:

you can try this, working for me in similar case

@import java.lang.String; val myTitle = { if(isEdit) "edit question" else "create question" }

<h1>
    @myTitle
</h1>


回答4:

Not so sure what you are asking, you can do this:

var myTitle = ""
if (isEdit)
    myTitle="edit question"
else
    myTitle="create question"

Or this:

val myTitle = if (isEdit) "edit question" else "create question"