public
Last active

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
class ApplicationController < ActionController::Base
...
# FORCE to implement content_for in controller
def view_context
super.tap do |view|
(@_content_for || {}).each do |name,content|
view.content_for name, content
end
end
end
def content_for(name, content) # no blocks allowed yet
@_content_for ||= {}
if @_content_for[name].respond_to?(:<<)
@_content_for[name] << content
else
@_content_for[name] = content
end
end
def content_for?(name)
@_content_for[name].present?
end
end
gistfile2.rb
Ruby
1 2 3 4 5 6
class PostsController < ApplicationController
def index
content_for :title, "List of posts"
...
end
end

This is exactly what I was looking for, thank you! Working for me in Rails 3.0.9.

My only suggestion would be to move it to a module ContentForInController so you don't clutter up your ApplicationController (I put mine in lib/content_for_in_controller.rb) and release it as a gem for easy reusability.

TylerRick, thanks for your comment. I have thought that if someone is interested in it, it can be worth releasing as a gem. It seems to be the time :)

Awesome work hiroshi. Kudos! I suggest you release it as a gem! it's the best time to do it!

For now, I'v not used rails for my projects. @kuroir, It's OK to release as a gem by you, if you wish. I'll appreciate to have my name or url for this gist on README :-)

I made a over basic gem to embed your code with style :)

I would love any feedback on how to inject the module a bit cleaner than calling send :include on ActionController::Base...

Thanks !

@clmntlxndr
Thanks. I just glad to see that my idea is usable for someone other than me :-)
As for the way to inject the module, I don't have any idea of better way for now.

Awesome gist!

Is there a way to prevent HTML to be escaped when appending the content? I am trying to do something like

  content_for(:head, render_to_string(:partial => "layouts/my_partial" ))

Sorry, just remembered about .html_safe...

I ended up changing the gist a bit to call html_safe before adding it to the content

Wouldn't that be html_safe ?

Mario Ricalde
Sent with Sparrow (http://www.sparrowmailapp.com/?sig)

On Saturday 7 de July de 2012 at 02:48 p.m., Felipe Sabino wrote:

Awesome gist!

Is there a way to prevent HTML to be escaped when appending the content? I am trying to do something like

content_for(:head, render_to_string(:partial => "layouts/my_partial" ))


Reply to this email directly or view it on GitHub:
https://gist.github.com/985457

Thank you so much for posting this! I was able to use this solution to override my page titles. Cheers.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.