#137 Use ViewComponent to Abstract reusable HTML. Blocks, Slots, Variables

12/07/2023

Don't repeat yourself (DRY) applies not only to Ruby code, but HTML and CSS too!

In this episode we will identify common HTML/CSS elements across some pages in our app and abstract it into a ViewComponent.

A View Component can accept variables and blocks of html to accomodate for the small differences of each of the pages.

View Components is an innovative approach for abstracting view logic elements in your Rails 7 frontend.

This might not be one of my greatest episodes, but I had to make it because it displays a great usecase for the right tool.

Episode source code: https://github.com/yshmarov/superails/pull/98/files
Based on this blogpost: https://viewcomponent.org/guide/slots.html

0:00 identify duplicate HTML/CSS
1:25 grenerate component and display variables
4:22 move duplicate HTML/CSS to ViewComponent
5:20 display content block in Component
6:20 optionally full width
8:35 reuse the Component in other parts of the app
10:11 ViewComponent Slots
12:57 Summary

0
Sign in to join the conversation