Home > other >  Sharing a partial from a different namespace
Sharing a partial from a different namespace

Time:04-01

rails 6.1

I am wanting to reference a partial in app/views/shared/ from another namespace.

# app/views/something/index.html.erb
<%= render partial: 'shared/my_partial' %>
# looks for app/views/shared/_my_partial.html.erb

# app/views/admin/something/index.html.erb
<%= render partial: 'shared/my_partial' %>
# looks for app/views/admin/shared/_my_partial.html.erb

When calling from within a namespace, the path always seems to be nested within that namespace, and cannot look outside of itself.

I have found this PR https://github.com/rails/rails/pull/22473 which would allow for denoting a leading / or ./ to specify absolute path, but it appears to be unmerged for many years which doesn't fill me with hope.

Does anyone know how I can achieve this apart from duplicating the views?

CodePudding user response:

There are no issues here, just a lack of understanding on how operating system paths work. To solve, just add a leading '/' to the path <%= render partial: '/shared/my_partial' %> But a nicer syntax is just to use

<%= render '/shared/my_partial' %>

You no longer need the full partial syntax

CodePudding user response:

Well it appears I've been able to resolve this by using render('path/to/partial') rather than render(partial: 'path/to/partial').

https://guides.rubyonrails.org/v6.1/layouts_and_rendering.html#rendering-an-action-s-template-from-another-controller

I am pretty confused as to why this method was not mentioned on any of the dozen articles I read trying to solve this issue, and I'm even more confused why the behavior between the two syntaxes varies so fundamentally.

  • Related