代码之家  ›  专栏  ›  技术社区  ›  Tim Sullivan

Rails 5.2+Webpacker:在javascript中呈现部分内容

  •  5
  • Tim Sullivan  · 技术社区  · 6 年前

    我有一个javascript文件(从技术上讲是刺激性的,但我认为这并不重要),我想在其中包含一个片段的内容,作为它稍后附加的HTML。

    enabled support for ERB with Webpacker ,但是打电话给 <%= render partial: 'shared/condition' %> 没用。它只是悄悄地无法产生结果。js文件并包含它。

    此代码不起作用:

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

    它不是渲染器。但是,渲染错误,因为这是可行的:

    const html = `<%= ApplicationController.renderer.render inline: 'something' %>`
    

    共享/_条件的内容。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、with the u、with the。html。雇员再培训局。我试过渲染 template: file: ... 我被难住了。

    半相关:是否有地方我可以看到产生的任何错误?日志显示编译总体上成功了,但没有生成它所在的控制器。我找不到任何明显的错误日志。

    埃塔:正在开发中。日志,显示如下:

    [Webpacker] Compiling…
      Rendered shared/_condition.html.erb (36.1ms)
    [Webpacker] Compiled all packs in /Users/timsullivan/dev/thing/public/packs
    

    ... 因此,它似乎确实呈现了部分,但却呈现了某种控制器。js文件未包含在组合应用程序中。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
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Ryan Clark    6 年前

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

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

    更详细的解释如下: https://stackoverflow.com/a/1623813/695186

    推荐文章