With web components coming to browsers soon and most JavaScript MV*s already using them, it seemed the right time to figure out how to do this in Rails. We can do this by making extensive use of partials.
In Handlebars, components can be inline or block form by creating them with or without a {{yield}}
respectively. Rails has the same configuration. The differences are how the partial is added to the view and how locals are passed to it.
In this gist, I have created a component generator. This will create the Slim and SCSS files for your component and update a SCSS file (a pattern I have used at work) with the correct @import
. The command for doing this is:
Inline component:
rails generate component <NAME>
Block component:
rails generate component <NAME> --block
The name you pass in will be turned into an underscored name, so my-component
turns into my_component
; The only option is to pass in the --block
flag to indicate that this partial should be in block form with a yield
as described below. Once the files have been created, we can then modify these generated files to build up our UI. I have added some examples to this gist.
Lastly, in our view files, we render our components. A block level component, or section
, requires the layout:
symbol, and also the locals:
hash when passing locals. Anything nested under the do
will be rendered inside the yield
of the section. An inline component does not have the same requirements and locals can simply be passed using symbols in key/value pairs.
Hope you find this useful and that it saves you from writing the same markup over and over. Remember try not to overkill it with this, this is a server-side rendered app; you might take hits to your performance if you're doing extensive view logic. Best of luck.