首页 > 解决方案 > 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 中:

something_controller.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

标签: ruby-on-railswebpackwebpacker

解决方案


假设您将渲染的部分附加到带有 jquery 或其他内容的元素,您需要转义 erb 标记的内容。

尝试这个:"<%= escape_javascript(render("/path/after/views/condition")) %>"

这里有更详尽的解释:https ://stackoverflow.com/a/1623813/695186


推荐阅读