在 Webpacker 中使用 Rails 6 中的 Bootstrap 图标

Gre*_*reg 13 css ruby-on-rails twitter-bootstrap bootstrap-4 webpacker

我想在测试版“Bootstrap 的官方开源 SVG 图标库”中使用 Bootstrap 图标。https://icons.getbootstrap.com/。这适用于 Rails 6 中的 Bootstrap 4。

我尝试了各种导入并包含在 application.js 和 application.scss 中,但没有成功

我该如何实现?

cec*_*p64 17

您也可以通过 CSS 使用它,我觉得它对旧的字形图标支持既方便又熟悉。首先,添加引导图标:

yarn add bootstrap-icons
Run Code Online (Sandbox Code Playgroud)

然后,只需将其导入到您的application.js文件中:

import 'bootstrap-icons/font/bootstrap-icons.css'
Run Code Online (Sandbox Code Playgroud)

最后,无论你想在哪里使用它,只需使用一个<i>标签:

<i class="bi bi-plus-circle"></i>
Run Code Online (Sandbox Code Playgroud)

应该是这样!


Gre*_*reg 10

我在此 GitHub讨论中找到了解决方案的基础,@chriskrams 提供了关键信息。

我跑去yarn add bootstrap-icons安装图标。

然后我在app/helpers/application_helper.rb. 空module ApplicationHelper是自动创建的。

module ApplicationHelper
  def icon(icon, options = {})
    file = File.read("node_modules/bootstrap-icons/icons/#{icon}.svg")
    doc = Nokogiri::HTML::DocumentFragment.parse file
    svg = doc.at_css 'svg'
    if options[:class].present?
      svg['class'] += " " + options[:class]
    end
      doc.to_html.html_safe
  end
end
Run Code Online (Sandbox Code Playgroud)

node_modules/bootstrap-icons/icons/ 是纱线安装图标的地方。

<%= icon("bicycle", class: "text-success") %>例如,使用图标。

您还可以在 app/node_modules/bootstrap-icons/icons/


Die*_*ego 10

您需要覆盖默认字体定义以加载适当的路径

yarn add bootstrap-icons
Run Code Online (Sandbox Code Playgroud)

然后添加到您的application.scss

@import "bootstrap-icons/font/bootstrap-icons";
@font-face {
  font-family: "bootstrap-icons";
  src: font-url("bootstrap-icons/font/fonts/bootstrap-icons.woff2") format("woff2"),
    font-url("bootstrap-icons/font/fonts/bootstrap-icons.woff") format("woff");
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用它:

<i class="bi bi-plus-circle"></i>
Run Code Online (Sandbox Code Playgroud)

确保您Rails.application.config.assets.paths << Rails.root.join('node_modules')config/initializers/assets.rb