javascript 如何从 rails 应用程序的 assets/images 文件夹中获取图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10263518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to fetch image from the assets/images folder in a rails app
提问by banditKing
I have been searching and searching for this answer. But I cannot seem to make this work, several hours now. Please please help me.
我一直在寻找和寻找这个答案。但我似乎无法完成这项工作,现在几个小时了。请帮助我。
I'm a webpage of my rails app, I am trying to show an image saved in my assets folder @app/assets/images/rails.png.
我是我的 rails 应用程序的网页,我正在尝试显示保存在我的资产文件夹中的图像 @app/assets/images/rails.png.
I have a javascript file with the following function that constructs html. Inside this function, I'd like to pass the link to the image. This is the code I have currently.
我有一个具有以下构造 html 函数的 javascript 文件。在这个函数中,我想将链接传递给图像。这是我目前拥有的代码。
function addToInfoWindow(infoWindowContent)
{
infoWindowString = '<div class="infoWindow">'+
**'<img src="/assets/images/rails.png" />'+**
'<p>'+infoWindowContent+'</p>'+
'<p><a href="http://www.google.com">See here</a></p>'+
'<p><a href="http://www.google.com">Upload a photo</a></p>'+
'</div>';
infoWindow.setContent(infoWindowString);
}
As you can see above in the code the bold part is the problem. I've tried several different combinations of url strings to access that image file but the image does not show up in the html element.
正如您在上面的代码中看到的,粗体部分是问题所在。我尝试了几种不同的 url 字符串组合来访问该图像文件,但该图像未显示在 html 元素中。
I've looked and looked, tried rails helper functions such as image_url('rails.png')
. But I must be putting them in the wrong place. Can someone please help me. Please show me where , what function in the above code I need to add to fetch the image at /assets/images/rails.png
so that it's url is placed in the highlighted part above and it shows in my view.
我看了又看,尝试过 Rails 辅助功能,例如image_url('rails.png')
. 但我一定是把它们放在了错误的地方。有人可以帮帮我吗。请告诉我在哪里,我需要在上面的代码中添加什么函数来获取图像,/assets/images/rails.png
以便它的 url 放置在上面突出显示的部分中,并显示在我的视图中。
回答by klump
If you want to you use the rails helpers you need to "upgrade" your javascript files to erb.
如果您想使用 rails 助手,您需要将您的 javascript 文件“升级”到 erb。
Just rename them from whatever.js
to whatever.js.erb
. Now rails will execute all the erb code (stuff between <%= and %>) before delivering the file.
只需将它们从 重命名whatever.js
为whatever.js.erb
。现在 rails 将在交付文件之前执行所有 erb 代码(<%= 和 %> 之间的内容)。
So you can do like this:
所以你可以这样做:
<img src="<%= asset_path( 'rails.png' ) %>" />
More information, see 2.2.3.
更多信息,见 2.2.3。
回答by DanS
You won't be able to use the rails helpers like image_tag in pure javascript - append .erb and use asset_path (see klump's answer)
您将无法在纯 javascript 中使用像 image_tag 这样的 rails 助手 - 附加 .erb 并使用 asset_path (请参阅 klump 的答案)