如何在 Rails 应用程序中创建模块化 UI 单元(组件)?
how to create modular UI units (components) in Rails app?
假设我们需要为 Rails 应用程序创建简单的 UI 组件,例如 header。我们将从创建多个文件开始:
1) app/views/partials/_header.erb
2) app/assets/stylesheets/_header.scss
3) app/assets/javascript/_header.js
然后我们需要将它们包含在适当的视图或清单文件中。
问题:
有没有简单的方法可以将这些文件移动到一个文件夹中?例如:
app
|-- ui_components
| |-- header
| | |-- view.erb
| | |-- style.scss
| | |-- script.js
并且,在 .scss
的情况下,通过执行以下操作将它们包含在 app/assets/stylesheets/application.scss
中:
@import "ui_components/header/style"
@import "ui_components/footer/style"
...
与 .js
相同。
谢谢。
View Component 支持,并且开箱即用的捆绑资源仍然有限。
我设法让它与 细胞一起工作 Gem
gem "cells-rails"
单元格 gem 允许您将视图组件放入 app/cells
,参见 http://trailblazer.to/gems/cells/
在你的 application.rb
你需要
def self.cells_with_assets
all_cell_file_names = Dir.glob("app/cells/**/*.rb")
all_cell_file_names.map do |f|
f.match(/app\/cells\/([a-z_\/]*)\.rb/)[1].classify
end
end
config.cells.with_assets = Application.cells_with_assets
要使其与 SCSS 一起使用,您还需要确保包含来自那里的文件,因此在您的 application.scss
中执行:
/* Include all SCSS Files in the cells directory
*= require_tree ../../cells
*/
当然,我现在建议使用 ActionView::Component
,因为它现在是 rails 核心的一部分,因为 5.x(不确定)。
将css、html和js捆绑在一起的概念在vuejs等javascript框架中经常使用,其中'languages'三个可以包含在一个"single-file-component".
我知道这不是你要问的,但既然你表达了捆绑的愿望css/html/js,你不妨考虑一下vuejs单文件组件。它们在整个应用程序中非常可重用,具有自己的风格和行为。
假设我们需要为 Rails 应用程序创建简单的 UI 组件,例如 header。我们将从创建多个文件开始:
1) app/views/partials/_header.erb
2) app/assets/stylesheets/_header.scss
3) app/assets/javascript/_header.js
然后我们需要将它们包含在适当的视图或清单文件中。
问题:
有没有简单的方法可以将这些文件移动到一个文件夹中?例如:
app
|-- ui_components
| |-- header
| | |-- view.erb
| | |-- style.scss
| | |-- script.js
并且,在 .scss
的情况下,通过执行以下操作将它们包含在 app/assets/stylesheets/application.scss
中:
@import "ui_components/header/style"
@import "ui_components/footer/style"
...
与 .js
相同。
谢谢。
View Component 支持,并且开箱即用的捆绑资源仍然有限。
我设法让它与 细胞一起工作 Gem
gem "cells-rails"
单元格 gem 允许您将视图组件放入 app/cells
,参见 http://trailblazer.to/gems/cells/
在你的 application.rb
你需要
def self.cells_with_assets
all_cell_file_names = Dir.glob("app/cells/**/*.rb")
all_cell_file_names.map do |f|
f.match(/app\/cells\/([a-z_\/]*)\.rb/)[1].classify
end
end
config.cells.with_assets = Application.cells_with_assets
要使其与 SCSS 一起使用,您还需要确保包含来自那里的文件,因此在您的 application.scss
中执行:
/* Include all SCSS Files in the cells directory
*= require_tree ../../cells
*/
当然,我现在建议使用 ActionView::Component
,因为它现在是 rails 核心的一部分,因为 5.x(不确定)。
将css、html和js捆绑在一起的概念在vuejs等javascript框架中经常使用,其中'languages'三个可以包含在一个"single-file-component".
我知道这不是你要问的,但既然你表达了捆绑的愿望css/html/js,你不妨考虑一下vuejs单文件组件。它们在整个应用程序中非常可重用,具有自己的风格和行为。