简体   繁体   English

如何使用Rails中的gem布局?

[英]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. 我正在制作一个宝石https://github.com/BDMADE/college-admin ,这是一个简单的管理模板布局,我正在制作这个宝石,为什么,我想在我的几个Rails应用程序中重复使用。

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. 但是,当我从demo项目的欢迎控制器致电时,确实显示了此错误。

在此处输入图片说明

So that, My question is how to use my layout(which is laid in college-admin gem) in this controller ? 因此,我的问题是如何在此控制器中使用我的布局(放置在college-admin gem中)? Should I any change in college-admin gem to display it's layout ? 我应该更改college-admin gem来显示其布局吗?

You need an engine which is a gem with added integration in to the Rails stack. 您需要一个引擎 ,它是在Rails堆栈中添加了集成的宝石。

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. Rails应用程序实际上只是一个“增压”引擎,Rails :: Application类从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: 我得到了解决方案:只需在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' 从控制器: layout 'main'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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