gpt4 book ai didi

javascript - 将 CSS 和 JS 限制为 Rails 引擎

转载 作者:行者123 更新时间:2023-11-28 00:48:31 25 4
gpt4 key购买 nike

我创建了一个 Rails 引擎,它的 CSS 和 Javascript 正在改变主机应用程序布局。

有没有一种方法可以在不更改整个应用程序的情况下将 Assets 限制在引擎 View 中?

最佳答案

您可以使用类作为命名空间来限定您的 css 和 javascript。

例如,如果您这样设置布局:

<!DOCTYPE html>
<html>
<head>
# ...
</head>
<% content_tag :body, class: [controller_name, action_name]
do %>
<%= yield %>
<% end %>
</html>

这将允许您创建仅适用于一个 Controller 和/或操作的 CSS 规则:

body.users h1 {
color: "blue"
}

body.users.show h1 {
color: "black"
}

您还可以通过使用委托(delegate)来确定 javascript 的范围。

$('body.users').on('click', 'h1', function(){
alert("This works on any action for the users controller");
});

$('body.users.show').on('click', 'h1', function(){
alert("This should only work on the show view");
});

您可以通过创建一个输出带有“作用域”类的正文标签(或任何真正的标签)的助手,将相同的原则应用于引擎:

# /lib/my_engine/helpers/tags_helper.rb
module MyEngine
module TagsHelper
def body_tag(**options, &block)
options[:class] ||= []
options[:class] << "my_engine" if controller.try(:my_engine_controller?)
content_tag(:body, options) { yield }
end
end
end

# /lib/my_engine/engine.rb
require 'helpers/tag_helper'

module MyEngine
class Engine < ::Rails::Engine
ActionView::Base.send :include, MyEngine::TagsHelper
end
end

这假设您引擎中的 Controller 响应 my_engine_controller?(就像 Devise 响应 devise_controller?

然后它只需要在布局中实现:

<!DOCTYPE html>
<html>
<head>
# ...
</head>
<%= body_tag do %>
<%= yield %>
<% end %>
</html>

并且您需要将 css/js 的范围限定为 .my_engine

关于javascript - 将 CSS 和 JS 限制为 Rails 引擎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53398080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com