This is a weird requirement that may need another approach, but my brain is stuck.
I want to accomplish something like this:
class UsersController < ApplicationController
before_filter Proc.new { share_params :user_name }, :only => :show
render_djs
end
class ApplicationController < ActionController::Base
include ActionView::Helpers::CaptureHelper
def share_params(*shared)
content_for(:djs) { shared.inspect }
end
def self.render_djs
before_filter Proc.new {
render :inline => "<%= yield(:djs) %>" if request.format.djs?
}
end
end
I want to use content_for
because I may want to add content to the :djs
yield in other filters.
However, this code raises undefined method output_buffer=
.
I suppose I could use an instance variable, but this seems cleaner, doesn't it?
You need to use the #view_context
method to reach the view context and then you can do the same as you would do in a view:
view_context.content_for(:something, view_context.render(partial: 'some_partial'))
I found this helpful very much in case of setting title for my page.
I can just set content_for from controller
class PostsController < ApplicationController
def index
content_for :title, "List of posts"
...
end
end
https://gist.github.com/hiroshi/985457
https://github.com/clmntlxndr/content_for_in_controllers
If like me you are just looking to set content in the controller like a title, then it's probably better to just use a variable that's automatically passed to views and helpers. eg.
controller:
class AController < ApplicationController
before_action :set_title
private
def set_title
@title = 'Email Subscription'
end
end
and the helper:
module ApplicationHelper
def title_suffix
" - #{@title}" unless @title.nil?
end
end
and the template:
<!DOCTYPE html>
<html>
<head>
<title>Standard Title<%= title_suffix %></title>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With