简体   繁体   English

Rails 7 导入地图 - 如何将脚本注入 HTML 模板?

[英]Rails 7 Import Maps - How do I inject a script into HTML template?

In rails 6 with webpacker you could throw in a <%= javascript_pack_tag 'alerts' %> in a view or template to inject some js.在带有 webpacker 的 rails 6 中,您可以在视图或模板中添加<%= javascript_pack_tag 'alerts' %>以注入一些 js。

How does this work with import maps and rails 7?这如何与导入地图和 Rails 7 一起使用?

As long as the code is correctly in the import map, you can reference it with:只要代码在 import map 中正确,就可以引用它:

<script type="module">import "/assets/custom/alerts.js";</script>

Presuming the file is app/javascript/custom/alerts.js假设文件是app/javascript/custom/alerts.js

Referenced in config/importmap.rb as:config/importmap.rb中引用为:

pin_all_from "app/javascript/custom", under: "custom"

And imported into the application.js:并导入到 application.js 中:

import "custom/alerts"

Edit: I now think this is an antipattern in Rails 7. It is very easy to use Stimulus controllers instead.编辑:我现在认为这是 Rails 7 中的反模式。使用 Stimulus 控制器非常容易。

Stimulus Handbook For reference刺激手册供参考

For example, to dismiss an alert when a user clicks the "x"例如,当用户单击“x”时关闭警报

// app/javascript/alerts_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    dismiss () {
        this.element.style.display = 'none';
    }
}
<div data-controller="alerts">
    <h2> Alert! </h2>
    <span data-action="click->alerts#dismiss"><i class="fas fa-times"></i></span>
</div>

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

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