6

I know that by default, views in Rails use the template provided in application.html.erb. However, there's one view that I wouldn't like to use the template provided in application.html.erb, but rather write all the HTML in that view itself. Is that possible to do?

5 Answers 5

10

At the end of your controller action, add:

render :layout => false
Sign up to request clarification or add additional context in comments.

3 Comments

Should that line go before or after the line render "tree.html.erb"?
on the same line render "tree.html.erb", :layout => false
but, if your action is already called tree, you can skip the "tree.html.erb" part, and just call render :layout => false
4

For a specific action:

class SomeController < ApplicationController
  def my_custom_action
    render layout: false
  end
end

1 Comment

If you name your controller and actions the same way you name your views, you won't need to specify tree.html.erb. If you do, write it like this: render 'tree.html.erb', layout: false
2

Sure, in your action do something like this:

def action
  render :layout => false
end

This assumes there are other actions in your controller which do need the layout. Otherwise, I would specify layout false in the controller root.

If you have multiple actions which don't need a layout, I believe you can do

layout false, :only => [ :action1, :action2 ]

1 Comment

Thanks for the last bit.. might come in useful later!
2

You can achieve the same thing using custom layouts.

e.g. For WelcomeController

  1. Create a custom layout file named welcome.html.erb in app/views/layout/. Write your layout code there(don't forget the yield). Due to rails Convention over Configuration feature when rails renders any view mapped to WelcomeController, welcome.html.erb will override the default application.html.erb layout.

  2. If you want to name your custom layout file differently. Rails allows you to do that as well. Name your layout file as mylayout.html.erb. In WelcomeController, add the following code

    class WelcomeController < ApplicationController

    layout 'mylayout'

    ....

    end

  3. If you want custom layout for only a specific action, then on the last line of action write render layout: 'mylayout'

Comments

0

You have to be sure that your controller inherits from ApplicationController

class MyCustomController < ApplicationController

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.