简体   繁体   English

动态更新rails image_path

[英]updating rails image_path dynamically

I am using the rails js helper image_path to update an images source using javascript. 我正在使用Rails js帮助程序image_path使用javascript更新图像源。

The actual string for the new img src path lives inside of a variable and I need to inject that into the image_path string below, which has been giving me problems. 新img src路径的实际字符串位于变量内部,我需要将其注入下面的image_path字符串中,这一直给我带来了问题。

Here is what I'm working with: 这是我正在使用的:

Object: 宾语:

var bike = { image: "bikes/diamondback/diamondback-29-ht.png"} var bike = {图片:“ bikes / diamondback / diamondback-29-ht.png”}

Image path: 图片路径:

$('.ga-recommended-bike').attr('src', "<%= image_path 'bikes/diamondback/diamondback-29-ht.png' %>")

I've been trying to do something like this to inject the url into the image path: 我一直在尝试做这样的事情来将URL注入图像路径:

$('.ga-recommended-bike').attr('src', "<%= image_path `${bike.image}` %>")

also tried the non es6 way 也尝试了非es6方式

$('.ga-recommended-bike').attr('src', "<%= image_path " + bike.image + " %>")

I think the problem is the intermingling of the rails and js code. 我认为问题是Rails和js代码混杂在一起。

Does anyone know of a good way to solve this using rails and javascript? 有谁知道使用rails和javascript解决此问题的好方法?

Is there a reason you need the ruby code in the JS? 您是否有理由需要JS中的ruby代码? That probably won't work. 那可能行不通。 But if you must pull data from the dom to render data via js, why not use the ruby code in the view in say a data attribute and use that in the javascript. 但是,如果您必须从dom中获取数据以通过js呈现数据,为什么不在视图中使用data属性来在视图中使用ruby代码,并在javascript中使用它。

<div id="my-data-thing", data-image-path="<%= image_path 'bikes/diamondback/diamondback-29-ht.png' %> ></div>

Unfortunately I wasn't able to get the string injection to work, but here's how I got to a working solution (that still doesn't answer this question): 不幸的是,我无法使字符串注入正常工作,但是这是我如何获得有效的解决方案的方法(仍然无法回答该问题):

I included the full image path url in the object variable. 我在对象变量中包含了完整的图像路径URL。 The file this lives in must be .js.erb 该文件所在的文件必须是.js.erb

  var bikes = {
    diamondbackOverdrive29: {
      image: "<%= image_path 'bikes/diamondback/diamondback-29-ht.png' %>",
      price: "",
      make: "",
      model: "",
      features: []
    }
  }

Then I'm able to just call bikes.diamondbackOverdrive29.image 然后我就可以打电话给bikes.diamondbackOverdrive29.image

So I'm going to have to declare the full image path for each item, but it seems okay for now, and pretty clean still. 因此,我将必须为每个项目声明完整的图像路径,但是现在看来还可以,而且还很干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM