Skip to content

Should you use content_for inside a component template? #1591

Answered by boardfish
TheEnzoMar asked this question in Q&A
Discussion options

You must be logged in to vote

It feels like an anti-pattern, even though it seems to work, as it couples a component to some external thing.

I think you're right on the money here. If you're using content_for, then chances are you're doing something at a global level, perhaps involving layouts or needing to pass things around in a way you might find uncomfortable. In the past I've avoided the need for content_for by having layouts render a component:

<%# app/views/layouts/some_layout.html.erb %>
<%= render NavbarComponent.new %>
<%= yield %>

This way, if the data you'd pass to content_for changes on a controller basis, you can use a different template that renders the same component with some small tweak – maybe tha…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by TheEnzoMar
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants