Undistraction
Undistraction

Reputation: 43351

Relative Paths From Partials Referencing Other Partials

I am using a (primary) partial:

<%= render partial: 'shared/page/head' %>

Which makes use of other (secondary) partials:

<head>
  <%= render partial: 'shared/page/head/title' %>
  <%= render partial: 'shared/page/head/meta' %>
  ...
  <%= render partial: 'shared/page/head/fonts' %>
  ...
  <%= render partial: 'shared/page/head/google_analytics' %>
</head>

As you can see I'm currently using paths relative to app/view for these secondary partials even though they are sitting in the same directory as the primary partial.

I've tried using relative paths:

<%= render partial: 'title' %>

Or

<%= render partial: './title' %>

But neither work.

Is there a way to have a partial resolve partials it uses using a relative path?

Upvotes: 26

Views: 10252

Answers (3)

user1519372
user1519372

Reputation: 41

I wrote a helper method for this which works perfectly:

def render_relative_partial(relative_path, option={})
    caller_path = caller[0].split(".")[0].split("/")[0..-2].join("/")
  path = caller_path.gsub("#{Rails.root.to_s}/app/views/","") + "/#{relative_path}"

  option[:partial] = path
  render option
end 

Upvotes: 1

Andreas
Andreas

Reputation: 998

As mentioned by another poster, prepend_view_path can be used to achieve this.

Here is how to implement it:

controllers/shared_page_controller.rb

class SharedPageController < ActionController::Base
  before_action :set_view_paths

  # ... 

  private

  def set_view_paths
    prepend_view_path 'app/views/shared/page/head'
  end
end

views/shared/page/head.html.erb

<head>
  <%# This will try to find the partial `views/shared/page/head/title.html.erb` %>
  <%= render partial: 'title' %>
  <%= render partial: 'meta' %>
  <%# ... %>
  <%= render partial: 'fonts' %>
  <%# ... %>
  <%= render partial: 'google_analytics' %>
</head>

Now Rails will not only look for partials in app/views, but also app/views/shared/page/head.

Upvotes: 1

Lawson Kurtz
Lawson Kurtz

Reputation: 636

This might be one solution to your problem: http://apidock.com/rails/ActionController/Base/prepend_view_path

Upvotes: 3

Related Questions