如何在 Rails 7 esbuild 应用程序中显示 Bootstrap 5.3 弹出窗口?

问题描述 投票:0回答:1

当我使用 Bootstrap 创建一个全新的 Rails 7 应用程序时,模态框可以开箱即用,但弹出窗口不能。我怎样才能让他们工作?

Rails 7.1.2、esbuild、Bootstrap 5.3.2:

rails new --database sqlite3 --javascript esbuild --css bootstrap bootstrap_test
cd bootstrap_test
bin/setup
rails g scaffold page
edit app/views/pages/index.html.erb #see below
bin/dev
#app/views/pages/index.html.erb
<h1 class="display-1">Hello Bootstrap</h1>

<div class="modal fade" id="exampleModalXl" tabindex="-1" aria-labelledby="exampleModalXlLabel" style="display: none;" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-4" id="exampleModalXlLabel">If you can see this...</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Modals are working 🎉
      </div>
    </div>
  </div>
</div>


<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModalXl">Modal test</button>
<br>
<button type="button" class="btn btn-danger" data-bs-toggle="popover" data-bs-title="If you can see this..." data-bs-content="Popovers are working 🎉">Popover test</button>

根据Bootstrap文档

出于性能原因选择加入弹出窗口,因此您必须自己初始化它们

我尝试输入他们建议的初始化代码,但我得到了

ReferenceError: Can't find variable: bootstrap
:

console.log('Loading popovers...')

const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

有一次我尝试通过 Stimulus 初始化它们,但我也无法使其工作。

我错过了一些明显的东西吗?

javascript ruby-on-rails bootstrap-5 esbuild
1个回答
0
投票

发布我的问题后,我发现了一个类似/相关的问题,这帮助我找到了a解决方案。

为了从我的应用程序中的 JS 文件引用

bootstrap
,我复制了主
import * as bootstrap from "bootstrap"
文件中的
application.js
命令...

//app/javascript/popovers.js

console.log('Loading popovers...')

import * as bootstrap from "bootstrap"

const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

然后我从我的主

application.js
导入该文件:

//app/javascript/application.js

// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import * as bootstrap from "bootstrap"
import "./popovers.js"

现在弹出窗口和模态框都显示了。我只需要弄清楚当我单击文档中的其他位置时如何关闭弹出窗口🤔

© www.soinside.com 2019 - 2024. All rights reserved.