ruby-on-rails - Rails 5.2 + Webpacker:在 javascript 中渲染部分内容
问题描述
我有一个 javascript 文件(something_controller.js.erb;从技术上讲是 Stimulus,但我认为这并不重要),我想在其中包含部分内容作为稍后将附加的 HTML。
我使用 Webpacker 启用了对 ERB 的支持,但是调用<%= 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:
半相关:在某个地方我可以看到生成的任何错误吗?日志显示编译通常成功,但是根本没有生成该控制器。我找不到任何明显的错误日志。
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 中:
为了在某处找到错误,我尝试运行:
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")) %>"
推荐阅读
- python - 如何使信号居中以从零开始
- r - 有没有办法在我的 R 中的道路网络分析中解决这个问题?
- amazon-ec2 - 如何将移动应用程序生成的流量(API 调用)列入 EC2 API 服务器的白名单/允许
- javascript - 您应该存储 Google 访问令牌吗?
- ios - UIActivityViewController 完成块问题。当用户“取消”消息时不会被调用
- c++ - 困难的硬币交换算法
- excel - 如何复制并找到最后 125 行?
- unit-testing - 数据库单元测试 - 如何模拟过程中的时间
- python - 在熊猫中跟踪具体的时间段
- python - 在文本文件中搜索变量,获取数据并为其分配一个变量(python)