Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using content_for inside a controller

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?

like image 797
Ivan Avatar asked Jun 05 '11 17:06

Ivan


3 Answers

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'))
like image 112
KARASZI István Avatar answered Oct 25 '22 11:10

KARASZI István


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

like image 45
ramkumar Avatar answered Oct 25 '22 11:10

ramkumar


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>
...
like image 33
Camden Narzt Avatar answered Oct 25 '22 11:10

Camden Narzt