Domanda

I am developing an engine with a controller and views, but I want to allow for the views to be overridden (this is simple enough as Rails::Engine allows for this by automatically prepending app/views from the main app to the view path for the engine). However, I want the overridden view to be able to refer to the view from the engine - for example, I want to "wrap" the engine's view with custom stuff in my app:

# main_app/app/views/engine/template.haml

# ... custom stuff here
= render template: 'engine/template'
# ... custom stuff here

The problem is, I can't find a way to refer to the engine's view once I override it... is it possible?

È stato utile?

Soluzione

Try rendering the file by providing the full path of the engine's template file.

  # in view
  <%= engine_view {|f| render file: f} %>

  # in helper
  def engine_view(&b)
     yield eval("__FILE__.gsub(Rails.root.to_s, YourEngine::Engine.root.to_s)",b.binding) 
  end

Altri suggerimenti

tihom's approach is good, but the block feels unnecessarily hacky (and rubocop won't like it). I prefer something like:

## in helper
def render_engine_view
  render file: caller_locations.first.path.gsub(Rails.root.to_s, YourEngine::Engine.root.to_s)
end

## in view
# ... custom stuff here
<%= render_engine_view %>
# ... custom stuff here
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top