Rails 3.1 的引擎资产
应该如何在 Rails 3.1 的引擎中提供资源?它们应该位于哪里并且可以自动包含吗?
How should one provide assets in an engine in Rails 3.1? Where should they be located and can they be included automatically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有引擎的资产文件夹的路径都会自动加载。
默认情况下不加载资源本身。这是可以理解的,因为加载是通过
require_tree .
完成的,它从当前文件夹(即主应用程序资源文件夹)加载所有 css/js,但没有提及任何有关引擎资源的内容。简单的解决方案是要求用户在 application.js/css 或其他需要的地方需要 js/css。由于路径已正确加载,用户只需指定资产的名称(我建议使用引擎的名称)。示例:
附加到
main_app/app/assets/javascripts/application.js
:如果您已将 js 拆分到不同的文件中,则您的文件
your_engine_name/app/assets/javascripts/your_engine_name.js< /code> 可以包含以下内容:
这将加载
your_engine_name/app/assets/javascripts/
中的所有 js 文件,作为“.”指的是本地文件夹(在本例中是引擎的 javascript 文件夹)。请注意,当设置
config.use_sprockets
时,ActionView::Helpers::AssetTagHelper.register_javascript_expansion
似乎没有任何效果。我希望他们至少会在这种情况下发出警告。如果您有一个 rake 任务来安装引擎,那么您可以附加到 application.js。
用户包含它的另一种方法是在 erb 布局中插入
<%= javascript_include_tag "your_engine_name" %>
。我不认为有办法让它自动插入
The paths to the all the engines' assets folders are automatically loaded.
The assets themselves are not loaded by default. This is understandable as the loading is done with
require_tree .
, which loads all css/js from the current folder (i.e. the main application assets' folder) but doesn't say anything about the engines assets.The easy solution is to ask the user to require the js/css in application.js/css or wherever else it is needed. As the paths are loaded correctly, the user only need to specify the name of your asset (I'd recommend using the name of your engine). Example:
Appended to
main_app/app/assets/javascripts/application.js
:If you have split your js in different files, your file
your_engine_name/app/assets/javascripts/your_engine_name.js
could have the following:This will load all js files in
your_engine_name/app/assets/javascripts/
, as the "." refers to the local folder (in this case the folder of your engine's javascripts).Note that
ActionView::Helpers::AssetTagHelper.register_javascript_expansion
appears not to have any effect whenconfig.use_sprockets
is set. I hope they'll at least put a warning in that case.If you have a rake task to install your engine, then you could do the append to application.js.
Another way for the user to include it is to insert
<%= javascript_include_tag "your_engine_name" %>
in the erb layout.I don't think there is a way to have it inserted automatically