简体   繁体   中英

How to use a layout from a gem in rails?

I am making a gem https://github.com/BDMADE/college-admin , It is a simple a layout of an admin template, I am making this gem, for why, I want to re-use in my several rails app.

My welcome controller:

class WelcomeController < ApplicationController
layout 'college-admin/main'

  def index
    @hello = 'Hello Word'
  end
end

My views:

<h1>Welcome#index</h1>
<p>Find me in app/views/welcome/index.html.erb</p>
<%= @hello %>

But when I call from my welcome controller of a demo project, it does shows this error.

在此处输入图片说明

So that, My question is how to use my layout(which is laid in college-admin gem) in this controller ? Should I any change in college-admin gem to display it's layout ?

You need an engine which is a gem with added integration in to the Rails stack.

Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the Rails::Application class inheriting a lot of its behavior from Rails::Engine.

You can create a new engine with:

bundle exec rails plugin new <NAME> --mountable --full --dummy-path=spec/dummy

I got the solution: Just use this on lib/college/admin.rb:

require "college/admin/engine"

before:

require "college/admin/version"

module College
  module Admin
    # Your code goes here...
  end
end

After the change:

require "college/admin/version"
require "college/admin/engine"

module College
  module Admin
    # Your code goes here...
  end
end

From the controller: layout 'main'

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