Ruby-on-rails 在公共文件夹中显示静态图像(rails 4)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26446989/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:57:45  来源:igfitidea点击:

Display static image in public folder (rails 4)

ruby-on-railsruby-on-rails-4

提问by Timothy Leung

I have some images in the public folder, I obtain the url /public/link/to/image.jpgin my controller. I want to display it in my view, so I passed the url to the view.

我在公共文件夹中有一些图像,我/public/link/to/image.jpg在控制器中获取了 url 。我想在我的视图中显示它,所以我将 url 传递给视图。

But how can I display it on the webpage?

但是我怎样才能在网页上显示它呢?

I searched through the post, most of them related to photos stored in assets folder, whichi can be retrieved by <%= image_tag image-url (filename) %>in view.

我翻了翻帖子,大部分都和assets文件夹里的照片有关,可以<%= image_tag image-url (filename) %>在view中检索。

So how could I display image in public folder in view?

那么如何在视图中显示公共文件夹中的图像?

回答by Jonathan Bowman

I just tested this out in one of my applications, adding an image to the public folder, and was able to render it in view by using:

我刚刚在我的一个应用程序中对此进行了测试,将图像添加到公共文件夹中,并且能够使用以下方法将其呈现在视图中:

<img src="/your_image_file_name.png">

<img src="/your_image_file_name.png">

I've never done it through the public folder before, but if I had to guess I'd say you don't need the "/public" part of the file path.

我以前从未通过公共文件夹完成过,但如果我不得不猜测,我会说您不需要文件路径的“/public”部分。

If I understand the question, that should do it - hope to have helped.

如果我理解这个问题,那就应该这样做 - 希望有所帮助。

回答by Andrius

You can also use Rails-way via <%= image_tag("/path/to/file.jpg") %>

您还可以通过使用 Rails-way <%= image_tag("/path/to/file.jpg") %>

For security reasons, image_tagcan only look inside /public, so you don't have to specify /publicin the path — it will get added automatically.

出于安全原因,image_tag只能查看 inside /public,因此您不必/public在路径中指定- 它会自动添加。

Remark- try always to store images in subfolders in /publicas it (image_tag) will not work if you omit /publicand simply pass the image filename to image_tag, like <%= image_tag("filename.jpg") %> <- in this case it will go search /assets/imagesfolder.

备注- 尝试始终将图像存储在子文件夹中,/public因为如果省略/public并简单地将图像文件名传递给它 (image_tag) 将不起作用image_tag,例如 <%= image_tag("filename.jpg") %> <- 在这种情况下它会去搜索/assets/images文件夹。

Solution in action:

行动中的解决方案:

  1. enter image description here

  2. enter image description here

  1. 在此处输入图片说明

  2. 在此处输入图片说明

回答by Gediminas

You can use:

您可以使用:

<%= image_tag('/link/to/image.jpg') %>

if your image is in publicdir, and link/to/ subdirs

如果您的图像在public目录中,并且链接/到/子目录

If it is in root public folder:

如果它在根公用文件夹中:

<%= image_tag('/image.jpg') %>