gpt4 book ai didi

ruby-on-rails - Rails 5.2 + Webpacker : rendering a partial inside javascript

转载 作者:行者123 更新时间:2023-12-04 06:16:22 24 4
gpt4 key购买 nike

我有一个 javascript 文件(something_controller.js.erb;技术上是 Stimulus,但我认为这并不重要),我想在其中包含部分的内容作为稍后将附加的 HTML。

enabled support for ERB with Webpacker ,但调用 <%= render partial: 'shared/condition' %> 不起作用。它只是悄悄地无法生成 .js 文件并将其包含在内。

此代码不起作用:

const html = `<%= ApplicationController.renderer.render partial: 'shared/condition' %>`

不过,这不是 renderer.render 错误,因为它有效:
const html = `<%= ApplicationController.renderer.render inline: 'something' %>`

shared/_condition.html.erb 的内容并不奇怪,并且没有变量:
<div data-controller='condition'>
<a href='#' data-action='condition#remove'><i class="fas fa-trash-alt"></i></a>
<a href='#' data-toggle="popover" data-target='condition.item' data-action='condition#doNothing'>Item</a>
<a href='#' data-toggle="popover" data-target='condition.value' data-action='condition#doNothing'>Value</a>
</div>

我尝试了所有我能想到的路径组合:app/views/shared/condition、/app/views/shared/condition、_、.html.erb。我试过渲染 template:file: ......我很难过。

半相关:有什么地方可以看到生成的任何错误吗?日志显示编译成功,但它所在的 Controller 根本没有生成。我找不到任何明显的错误日志。

ETA:在 development.log 中,出现:
[Webpacker] Compiling…
Rendered shared/_condition.html.erb (36.1ms)
[Webpacker] Compiled all packs in /Users/timsullivan/dev/thing/public/packs

...所以它似乎正在呈现部分,但 something_controller.js 文件没有包含在组合的 application.js 中:

something_controller.js is missing!

为了在某​​处找到错误,我尝试运行:
timsullivan$ rails assets:precompile
yarn install v1.6.0
(node:45691) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
[1/4] 🔍 Resolving packages...
success Already up-to-date.
✨ Done in 0.49s.
Webpacker is installed 🎉 🍰
Using /Users/timsullivan/dev/thing/config/webpacker.yml file for setting up webpack paths
Compiling…
Compiled all packs in /Users/timsullivan/dev/thing/public/packs

最佳答案

假设您使用 jquery 或其他东西将呈现的部分附加到元素,您将需要转义 erb 标记的内容。

试试这个:"<%= escape_javascript(render("/path/after/views/condition")) %>"
更详尽的解释在这里:https://stackoverflow.com/a/1623813/695186

关于ruby-on-rails - Rails 5.2 + Webpacker : rendering a partial inside javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616057/

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