23

我正在使用(主要)部分:

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

它利用了其他(次要)部分:

<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>

正如您所看到的,我目前正在使用相app/view对于这些次要部分的路径,即使它们与主要部分位于同一目录中。

我试过使用相对路径:

<%= render partial: 'title' %>

或者

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

但两者都不起作用。

有没有办法使用相对路径进行部分解析?

4

3 回答 3

3

这可能是您的问题的一种解决方案:http: //apidock.com/rails/ActionController/Base/prepend_view_path

于 2014-03-19T13:22:19.330 回答
1

我写了一个辅助方法来实现它。听起来像完美的工作。

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 
于 2019-05-26T03:28:34.843 回答
0

正如另一张海报所提到的,prepend_view_path可以用来实现这一点。

以下是如何实现它:

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>

现在 Rails 不仅会app/viewsapp/views/shared/page/head.

于 2019-12-20T08:50:49.007 回答