玩!框架:在单独的 JavaScript 文件中使用 URL 的最佳实践?
我目前正在重新组织一个Play! JS较多的项目 HTML 模板文件中的代码。该代码应移至外部 JS 文件具有更好的可读性和更快的页面加载时间。然而, 当我刚刚在 public 文件夹中创建一个 JS 文件时,所有 @{Controller.method} 链接替换不再起作用。我是 考虑从 HTML 调用一些初始化函数 只提供所需 URL 的模板,
initialize({ "Application.doThis" : "@{Application.doThis}"})
但是对于任何 URL 来说,这都变得非常麻烦且容易出错 这是添加的。另一件事是,I18N 也不再起作用。所以 对于这样的场景,您有自己的最佳实践是什么? JS 代码位于单独的文件中,但仍想使用 URL 生成和 你的 JS 中有 I18N 吗?
I am currently reorganizing a Play! project where there is a lot of JS
code in the HTML template files. This code should be moved to external
JS files for better readability and faster page loading times. However,
when I just create a JS file in the public folder, all the
@{Controller.method} link replacements are no longer working. I was
thinking about calling some initialization function from the HTML
templates which just supplies the required URLs like
initialize({ "Application.doThis" : "@{Application.doThis}"})
however this is becoming very cumbersome and error-prone with any URL
that is added. Another thing is, that the I18N also no longer works. So
what is the best practice for scenarios like these, where you have your
JS code in a separate file but still want to use URL generation and
I18N in your JS?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在主模板中,生成一个“Javascript 路由器”,如下所示:
然后在任何“静态”javascript 文件中,使用此路由器:
In the main template, generate a 'Javascript router', something like:
And then in any 'static' javascript file, use this router:
诀窍是让框架解析您的 javascript、CSS 或静态目录中的任何其他内容。这是一个简单的解决方案。
添加
controllers.StaticParser
控制器:在您的
conf/routes
文件中添加:该路由中的正则表达式非常重要,否则您无法向请求添加路径。
要请求已解析的静态资源,例如 js 脚本,请使用:
不幸的是,您不能使用
#{script 'test.js' /}
格式,因为 script 标记会查找静态资源文件。为了纠正这种令人厌烦的情况,这里有一个对 script 标签的无耻修改:#{parsescript 'test.js'/}
标签。它应该转到/views/tags/parsescript.tag
:它的工作方式与
#{script /}
标记完全相同,但在返回文件之前解析文件:#{parsescript 'test.js' /}
人们同样可以无耻地破解
#{stylesheet /}
标签,但我认为我已经占用了足够的空间。The trick is to get the framework to parse your javascript, or your CSS, or anything else in the static directories. Here's an easy solution.
Add a
controllers.StaticParser
controller:To your
conf/routes
file add:The regexp in that route is very important, otherwise you can't add pathing to the request.
To request a parsed static resource, such as a js script, use:
Unfortunately, you can't use the
#{script 'test.js' /}
format, because the script tag looks for the static file. To correct that irksome-ness, here's a shameless hack of the script tag: the#{parsescript 'test.js'/}
tag. It should go to/views/tags/parsescript.tag
:It works exactly like the
#{script /}
tag, but parses the file before returning it:#{parsescript 'test.js' /}
One could equally shamelessly hack the
#{stylesheet /}
tag, but I think I've taken up enough space already.