I would like to set up a pair of style guides for the admin and public sections of a website.
Each will need its own layout which will contain a mixture of static html and calls to erb partials (so a static page won't cut it). I have no need of a controller(s) to serve these pages and I don't want what is effectively development-only content cluttering up the rest of the code. This got me wondering whether there is a way to render a layout directly.
Disclaimer: I appreciate this is not something I should do often/ever and I know there are a wealth of arguments for why this is a bad idea. I am interested in whether this is possible.
Is there a way for me to render a layout directly from routes.rb
without going through a controller?
By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.
Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
From the controller's point of view, there are three ways to create an HTTP response: Call render to create a full response to send back to the browser. Call redirect_to to send an HTTP redirect status code to the browser. Call head to create a response consisting solely of HTTP headers to send back to the browser.
It's a way to redirect incoming requests to controllers and actions. It replaces the mod_rewrite rules. Best of all, Rails' Routing works with any web server. Routes are defined in app/config/routes. rb.
For some weird reason I wanted to render a blank JS file for a while, and writing a controller felt like too much for this kind of hack. Thanks to @genkilabs 's answer, I used this 3 liner:
get 'analytics/some_file.js', to: -> (env) do
[200, { 'Content-Type' => 'application/javascript' }, ['']]
end
I wanted to do something really stupid once, so if you do too, try this working example.
match :movedpage, :to => proc { |env|
if Rails.env.production?
@remote_path = 'http://productionhost.com'
elsif Rails.env.staging?
@remote_path = 'http://staginghost.com'
else
@remote_path = 'http://localhost:3000'
end
[
200,
{"Content-Type" => "text/html"},
[File.read("public/moved_page.html").gsub('@remote_path', @remote_path)]
]
}, :via => :all
Where moved_page.html was a static page asking people up update their bookmarks and @remote_path just typed in a link like <a href="@remote_path">@remote_path</a>
. Note that <%= %>
won't work because you don't have view helpers in there.
So, theres enough rope to get yourself in trouble ^_^
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