Mohamad
Mohamad

Reputation: 35359

How do I use different partials and layouts in subfolders?

I need to use a single partial for anything inside my views/admin folder. My setup:

/app/views/
        + admin
            + accounts
            + users
        + layouts
            - application.html.slim
        + application
            - _header.html.slim
        + users
        + accounts

I have a partial called _header.html.slim in /views/application/. The partial is rendered from /views/layouts/application.html.slim.

I want to render a different _header.html.slim partial for anything under the /views/admin dir. I can create a new _header.html.slim and add it to /views/admin/accounts and /views/admin/users, but I don't want to repeat my self. I want a single partial for everything under admin.

How can I so this? I tried adding /views/admin/application and /views/admin/layouts folders hoping they would override the ones in the /view dir, but no luck.

Upvotes: 2

Views: 3951

Answers (2)

InternetSeriousBusiness
InternetSeriousBusiness

Reputation: 2635

layouts/application.html.slim:

- if controller.controller_name == "admin"
    == render :partial => "admin/header"
- else
    == render :partial => "application/header"

Upvotes: 2

jefflunt
jefflunt

Reputation: 33954

The structure of the folders themselves don't control which ones get run or applied - the folder structure is really just to help you organize it in a way that makes sense.

You could accomplish what you're looking for in a couple of ways, depending on your needs:

One way is to specify the layout (which includes the desired partials) in the controller, using the render :layout => 'some_layout_name' option as outlined here (skip to the heading "2.2.11.2 The :layout Option" for the specifics).

Another way is to set a variable in your action that contains, say, the name of the layout(s) or partial(s) you want to render, and in your view do something like:

<% if @custom_partial == "slim" %>
  <%= render :partial => 'header.html.slim' %>
<% end %>

So, either specify a custom layout (if you want the whole layout including partials to be custom), or set a flag variable that controls which partials get rendered at which time, and use that variable to control the flow of rendering in your view. Which of those options is right for you depends really on which is cleaner, most reliable, and makes sense for your project; that is, it's up to you to decide.

Upvotes: 0

Related Questions