Play 框架 2.x Scala 模板中的内联变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10473265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:09:11  来源:igfitidea点击:

Inline variable in the Play framework 2.x Scala template

scalaplayframeworkplayframework-2.0

提问by user1051870

How to create an inline variable in the Play framework 2.x Scala template? Path from the Play's guideis not clear to me:

如何在 Play 框架 2.x Scala 模板中创建内联变量?我不清楚Play 指南中的路径:

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

回答by Farmor

First you don't create a variable but a valuemeaning it's read only.

首先,您不创建变量而是创建一个值,这意味着它是只读的。

In your example you have created a value fullNamewhich is accessible inside the curly brackets.

在您的示例中,您创建了一个fullName可在大括号内访问的值。

@defining("Farmor") { fullName =>
  <div>Hello @fullName</div>
}

Will print Hello Farmor

将打印你好农夫

To define a value which is accessible globally in your template just embrace everything with your curly brackets.

要在模板中定义一个可全局访问的值,只需用大括号包含所有内容。

E.g.

例如

@defining("Value") { formId =>
  @main("Title") {
    @form(routes.Application.addPost, 'id -> formId) {
      @inputText(name = "content", required = true)
      <input type="submit" value="Create">
    }
  }
}

In the example you can use the value formIdanywere.

在示例中,您可以使用任何值formId

回答by OlivierBlanvillain

If you don't want to use the @definingsyntax you can define a reusable blockwhich will be evaluated every time you use it:

如果您不想使用该@defining语法,您可以定义 a reusable block,每次使用时都会对其进行评估:

@fullName = @{
  user.firstName + " " + user.lastName
}

<div>Hello @fullName</div>

With this same syntax you can also pass arguments to the block: https://github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html

使用相同的语法,您还可以将参数传递给块:https: //github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html

回答by user1051870

It's easy, span your block with code from the sample, then you will can use @fullNamevariable which has value:

很容易,使用示例中的代码跨越您的块,然后您将可以使用@fullName具有值的变量:

user.firstName + " " + user.lastName