简体   繁体   中英

Rails engine extending views, not overriding

I am aware that I can override an applications view from within an engine by simply creating the same file within the engine and removing it from the application (eg: 'users/show.html.erb').

However, what I want is to be able to extend the applications view, not override.

Lets say I have a yield inside 'users/show.html.erb' of the main application:

yield :foo

What I want is for the engine to specify the same file 'users/show.html.erb' and to have a content_for block

content_for :foo {}

Thereby, injecting some template data from the engines view, into the applications view.

Obviously, the above won't work as once it has found the template file in the application, it won't look for one in the engine.

Is there a way to make this work?

There is no way to extend views that way in Rails. You can however, accomplish this by using partials. In your engine, write a partial view file users/_show.html.erb and then render it in your app's view:

# app/views/users/show

# will look for a partial called "_show.html.erb" in the engine's and app's view paths.
render partial: 'show'

It's just as easy as your suggestion.

This gem tries to implement partial extension of views, but it works similarly to what I just described: https://github.com/amatsuda/motorhead#partially-extending-views-in-the-main-app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM