agmcleod
agmcleod

Reputation: 13621

Rails rendering layout only?

Just trying out a simple rails app, mostly going for an API backend with JSON, heavy client side app. So what i want to do is only render the layout, and have javascript code handle the url, and make the ajax request to get the json data. The following seems to work:

respond_to do |format|
  format.html { render :nothing => true, :layout => true }
end

However, since nothing is meant to render nothing, it feels kinda wrong. Is there a more proper way to just render the layout? Note that my layout does not have a yield.

Upvotes: 21

Views: 11401

Answers (6)

MaximusDominus
MaximusDominus

Reputation: 2107

(Copying Vasile's comment for better visibility.)

For rails 5.1, in order to render the layout without requiring a view template, you need to use

def index
  render html: '', layout: true
end

or with a custom layout

def index
  render html: '', layout: 'mylayout'
end

Per tfwright, this will also work:

def index
  render html: nil, layout: true
end

However, the following will not work:

render text: '', layout: 'mylayout' will give you an error because the view template index.html.haml does not exist.

render nothing: true, layout: 'mylayout' will give you an error because nothing:true is deprecated, and the index template does not exist (however, this works in rails 4.2)

render body: '', layout: 'mylayout' will render '' (no layout)

render plain: '', layout: 'mylayout' will render '' (no layout)

Upvotes: 20

skilleo
skilleo

Reputation: 2481

I needed something similar-- to display a layout template with no partial (where partials are handled clientside).

rails 4.2.0

respond_to do |format|
  format.html { render text: nil, layout: true }
end

Upvotes: 4

Devaroop
Devaroop

Reputation: 8023

Well, this worked for me in Rails 4.0:

render :text => "", :layout => true

Upvotes: 30

Valery Kvon
Valery Kvon

Reputation: 4496

render :file => "layout_file", :layout => false

Upvotes: 5

sameera207
sameera207

Reputation: 16629

Try this, this will render the response to a file called sample.html which could be a static html file.

and also you could have this file in a common location, so that you could loaded it to all the actions

have your static content in this page, and if you need a dynamic page you could have a .erb page too

in your method

def index
    @posts = Post.all

    respond_to do |format|
      format.html {render :file => "posts/sample"}
      format.json { render json: @posts }
    end
end

/post/sample.html

HTH

Upvotes: 4

MurifoX
MurifoX

Reputation: 15089

I believe if your application is just fetching JSON from the server, the format should be json and not html.

respond_to do |format|
  format.json @your_collection
end

Or put the format for all actions in your controller and just respond with the objects.

Upvotes: 0

Related Questions