Scala template set variable

2019-02-27 09:42发布

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 :-)

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-27 09:46

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"
查看更多
相关推荐>>
3楼-- · 2019-02-27 09:50

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>
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-27 09:51

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>
查看更多
冷血范
5楼-- · 2019-02-27 10:07

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.

查看更多
登录 后发表回答