开发者

Rails 3.1: Dynamic linking to images in the asset pipeline?

开发者 https://www.devze.com 2023-03-27 23:37 出处:网络
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 t

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:

  1. Can I maintain the subfolders therein?
  2. 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


  1. Yes, you can

  2. 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.

  1. 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
    
  2. add the new route to your action in routes.rb;

    get '/img', to: "car#image"
    
  3. 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消