trailblazer / cells

View components for Ruby and Rails.
https://trailblazer.to/2.1/docs/cells.html
3.07k stars 236 forks source link

"content_for" in Cells 4? #308

Closed ghost closed 9 years ago

ghost commented 9 years ago

Hi there,

I know that this is a very discussed topic, but I'm still having problems trying to use "content_for" inside of my cells views. I tried to use the "cells-capture" gem, but it seems to be outdated and throws an exception in the rails service initialization. I also tried to adapt its code and make it work with Cells 4 with no luck.

I saw another issue with a workaround to do this (https://github.com/apotonick/cells/issues/25), but is older than the capture gem, so I suppose and still have hope that you have another solution. :D

So... are there any way to use "content_for" in Cells 4? I'm getting a "NoMethodError" exception ("undefined method `append' for nil:NilClass").

Thanks in advance!

apotonick commented 9 years ago

We don't support #content_for (so far) - it completely defeats the purpose of encapsulating your view part. :laughing:

I won't implement a new version of cells-capture as I think content_for is a horrible idea and can easily be achieved with clean encapsulation:

  1. If you want CSS, JS or other assets to be placed in your global HTML, read this: http://trailblazerb.org/gems/cells/rails.html#asset-pipeline
  2. When in need to render a fragment from your cell somewhere else, just extract that to a separate state. Here's an example.
comment_cell = cell(:comment, @comment)
html = comment_cell.() # calls #show
more_html = comment_cell.(:more) # calls #more

Would that work for you?

ghost commented 9 years ago

Sure! It does the trick, even though it goes the other way round. I know is more correct thinking in the concept of encapsulation, but what I wanted to avoid was having a lot of references to the cell in my main app. Anyway, as I told you, it works and its a good solution.

Thanks for your help and quick response!

apotonick commented 9 years ago

Implementing a cells-content-for gem/module would actually be quite simple: You override the #cell helper and pass in the global AV instance as an option, somehow along this.

cell(:comment, @comment, action_view: self)

In the cell, you'd define a delegation to action_view.

class CommentCell < Cell::ViewModel
  delegates :action_view, :content_for

That should do the trick.