【问题标题】:How to use Ruby's asset_url in JS (Ruby interpolation in JS??)如何在JS中使用Ruby的asset_url(JS中的Ruby插值??)
【发布时间】:2014-12-29 18:18:53
【问题描述】:

好的,所以我有一个 JS 函数可以更改图像源,但我需要根据 Ruby 的资产管道对该图像源进行指纹识别。换句话说,我需要嫁给这段代码:

// JS code
changeImage("assets/How-to/" + step_to_remove + ".gif");

使用通常由

完成的指纹识别
# Ruby code
asset_path "How-to/#{step_to_remove}.gif"

我现在的权宜之计就是手动去除指纹,但我知道还有比这更好的方法。

【问题讨论】:

    标签: javascript ruby-on-rails asset-pipeline


    【解决方案1】:

    您可以使用 .js.erb 首先将您的脚本评估为 ERB:

    // app/assets/javascripts/my_script.js.erb
    changeImage("<%= asset_path(step_to_remove) %>");
    

    【讨论】:

    • changeImage("&lt;%= asset_path('How-to/step_to_remove.gif') %&gt;"); 还不够吗?
    • 我无法让它工作。这是错误:Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/How-to/step_to_remove.gif 请记住 step_to_remove 是一个 JS 变量
    • .js.erb 也不会工作,因为这是一个很小的 ​​sn-p,我只是将它包含在视图文件中
    • @james 那么问题出在哪里?当然你可以在你的视图中使用&lt;% %&gt;
    • 很抱歉,我不确定我是否沟通不畅。我将@Vucko 的建议放在&lt;script&gt; 标签中以供我查看。它得到了我在上面的评论中提出的错误。出现错误是因为 asset_path 代码有效,但我不知道如何插入 hte VARIABLE step_to_remove。如中所示,图像应该是 1.gif 或 2.gif,其中 1/2 是 step_to_remove,一个 JS 变量。这有帮助吗?谢谢@meagar!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2018-05-30
    • 1970-01-01
    • 2016-01-31
    • 2016-03-11
    • 2013-08-01
    相关资源
    最近更新 更多