如何使用 JavaScript 变量作为@Messages 的参数

How to use JavaScript variable as a param on @Messages

是否可以在@Messages中使用JS变量作为参数?当我使用它时,出现以下错误:

not found: value name

var name = "some name";
var title = "@Messages("message", name)"

不可能,@Messages在服务器端编译,javascript在客户端编译。它会在 javascript 之前编译,即使您将使用某些服务器端 js 引擎对其进行预编译。

这是在客户端计算消息的特殊模块,但我不确定它是否仍然适用于 Play 2.5:

https://github.com/julienrf/play-jsmessages

如果您尝试在 JS 代码中使用服务器数据或变量,则可以使用这种方法。在某些情况下,我需要我的 JS 有一个服务器项列表,所以在我的 whatever.scala.html 中,我创建了一个脚本标记并从服务器初始化一个 JS 变量,如下所示。

<script type="text/javascript">
  // get employee data from our server model - it needs to be converted to JSON for JS
  var employeeJsonString = @{Html(new Gson().toJson(model.getEmployeesAsJson()))};
  var employees = JSON.parse(exmployeeJsonString);
  // then you may use employees in JS code...
</script>

jsMessages 是一个很好的解决方案。

如果您想要更通用的解决方案来处理任何类型的代码,而不仅仅是消息,您可以试试这个:JavascriptRouting

它使您能够将 javascript 变量传递给对应用程序中端点的任何调用。但确实,您必须为您的消息设置播放路径。