Where to create the core (view) components?

In Phoenix there is a file called core_components.ex where we can define our core form components (or other very basic components). This is really handy because when we need to redisgn something the core design is DRY’d up.
Where would I put this components in Hanami? I was thinking about creating these in the app folder and then import them in my slices. Is this possible or are there better solutions for this?

Thanks for your question, @choallin!

(Firstly, for anyone following along at home, this file is what is currently generated as core_components.ex in new Phoenix apps. Taking a look at this helped me a lot with understanding this question.)

@choallin from the looks of core_components.ex, it seems you want some methods that can generate HTML output that you can use across all parts of your views?

In this case, defining these as view helpers in your Hanami app probably makes the most sense.

Helpers are just regular methods that you define in your app or slice’s Views::Helpers module. So you can use standard Ruby techniques to make helpers available across slices.

Let me know if this helps clear things up for you?

There are a few different places you can keep logic in our view layer, so if for any reason helpers don’t feel right to you, we can continue to discuss here :slight_smile:

Thanks! This is working. :slight_smile: Sorry for not making clear what the core_components.ex file is…

It is slightly annoying though that I can’t use erb for templates there. This would be nice so I could use iterations and if’s in the templates.
But helpers seem to be the way to go for my usecase

Glad you got something working, @choallin!

As a matter of fact, you can! Helper modules are included into a view’s scopes, and scopes allow you to render partials!

So in your helpers you can do this…

def my_core_component_helper
  render "core_components/my_helper"
end

… and it will render templates/core_components/_my_helper.html.erb (within the relevant app or slice).

Hope this helps you make things even tidier. Please let me know if you run into any issues!

1 Like