-
-
Save hiroshi/985457 to your computer and use it in GitHub Desktop.
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 |
class PostsController < ApplicationController | |
def index | |
content_for :title, "List of posts" | |
... | |
end | |
end |
Thank you so much for posting this! I was able to use this solution to override my page titles. Cheers.
Simple hack to make it work with a block - just do @_content_for||=yield
I cut-pasted this to make provide
for controllers - https://gist.github.com/hiroshi/985457
While this gist comes handy, it's too much just to use it to change the page titles. If someone wants to use this gist just to change the title of the pages dynamically it would be better just to put the following in the layout:
<title><%= @title || "default title" %></title>
With that approach one will just have to set the @title
instance variable in the controller, like this:
@title = 'My title'
Sorry to stir up an old topic, but what about memoizing the view_context? Will that cause other issues? Seems to work for me in rails 4.
def view_context
@view_context ||= super
end
delegate :content_for, to: :view_context
EDIT
Found out real quick: Don't do this, it breaks instance variable assignment...
seems broken on rails 4
Sorry, just remembered about .html_safe...
I ended up changing the gist a bit to call html_safe before adding it to the content