Rails 3.1: Dynamic linking to images in the asset pipeline?
I have ~ 500+ flag images that I previously kept in public/images/flags/
and public/images/flags_small/
. For each country in my Country model, I store the :iso_code
, which is the same as the name of the flag image that corresponds to it. For example, mx.png is the name of the Mexican flag because mx is the two-letter ISO code for Mexico.
I previously had a helper method that would return the html 开发者_运维百科to display the image based on the iso code of the country and whether I wanted the large or small flag.
With Rails 3.1, to comply with the asset pipeline, I'm under the impression that those images should go into the app/assets/images
folder. Following from this:
- Can I maintain the subfolders therein?
- How do I use image_tag to display the appropriate images?
Edit: solution The answer below was correct, but I didn't want to type that much code each time,so I created two helper methods:
def flag(country)
image_tag('/assets/flags/' + country.iso_code.downcase + '.png')
end
def small_flag(country)
image_tag('/assets/flag_small/' + country.iso_code.downcase + '.png')
end
Yes, you can
For example:
<%= image_tag 'flags/uk.gif' %>
As a quick solution to load images dynamically for Rails 5 (from a resource other than assets pipeline), imagine you have a controller called car.
add a new action (e.g. our action is called image) in your controller;
def image path = "C:/pics/.../test.jpg" # just a sample path to test send_file path, :content_type => 'image/jpg', :disposition => 'inline' end
add the new route to your action in routes.rb;
get '/img', to: "car#image"
and finally in your ERB file, create an image tag with;
<div> <%= image_tag url_for(:controller => "home", :action => "image") %> </div>
This is just to test the basics and you can make it parametrized (to load the image based on id, name, etc.)
精彩评论