PlayFramework HTML,变成Javascript? [英] PlayFramework HTML, variable into Javascript?
问题描述
想象一个简单的Play Action定义为
Imagine a simple Play Action defined as
def reactTest = Action {
request => Ok(views.html.hello("JOHN"))
}
和 hello.scala.html
看起来像这样,使用基本的React.js示例:
and the hello.scala.html
looks like this, using a basic React.js example:
@(name: String)
....
<div id="example"></div>
<script type="text/jsx">
React.render(
<h1>Hello, @name!</h1>, <---- NAME PARAMETER USED HERE
document.getElementById('example')
);
</script>
这很好,结果将是'Hello,JOHN!'页面。现在,我知道Scala代码在服务器上执行,客户端上的JS代码,但我想知道是否有办法传递 @name
参数使用相同的javascript(jsx)代码,如果此类代码位于单独的.js文件中,< div>
将如下所示:
This works fine and the result will be a 'Hello, JOHN!' page. Now, I know that the Scala code is executed on the server and the JS code on the client, but I am wondering if there would be a way to pass the @name
parameter to the same javascript (jsx) code if such code was in a separate .js file, and the <div>
would look like:
<div id="example"></div>
<script type="text/jsx" src="@routes.Assets.at("javascripts/hello.js"></script>
是否有办法将 @name
参数传递给 hello.js
?
Would there be a way to pass the @name
parameter to the script in hello.js
?
推荐答案
你可以在全局JS变量中保存你想要的任何东西,然后只要你需要就可以访问它。
You can save whatever you want in a global JS variable and then access it whenever you need.
例如,假设你想在你的脚本中使用一个用户对象。拥有这个html模板
For example, suppose you want to use a user object in your script. Having this html template
@(user: User)
<html>
<body>
<script>
var MyUserObject = {};
MyUserObject["name"] = "@user.name";
MyUserObject["age"] = @user.age;
</script>
<!-- ... -->
<script src="your_component.js"></script>
</body>
然后在你包含的js中你可以这样做:
then in your included js you could do something like this:
(function(user) {
alert("Hello " + user.name + ". You are " + user.age + " years old");
})(MyUserObject);
然后,您可以使用您想要使用的值的映射来改进它,或者可以将对象渲染为JSON并在JS端解析它:
You can then improve this using a map of the values you want to use or maybe rendering your object as JSON and parsing it on JS side:
def reactTest = Action {
request => Ok(views.html.hello(Json.toJson(user)))
}
// and then
@(user: String)
<html>
<body>
<script>
var MyUserObject = JSON.parse("@user");
</script>
<!-- ... -->
<script src="your_component.js"></script>
</body>
不完美,但更好而不是在JS文件上呈现IMO。
Not perfect, but better than rendering that on the JS files IMO.
这篇关于PlayFramework HTML,变成Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!