I have a problem with including images in my views using Ruby on Rails Webpacker. When i try to insert image in my view using html img tag and asset_pack_path i got an error. My
I had an issue with getting images to show up in Rails 6. I did this:
Add image to
assets/custom_folder/img_filename.file_extension
Uncomment two lines in javascript/packs/application.js
const images = require.context('../images', true)
const imagePath = (name) => images(name, true)
Then add your image to your erb file using this: (I had an index.html.erb view file)
<%= image_tag("custom_folder/file_name.file_extension")%>
This worked for me, hope it helped.
Check out this link
It looks like the path is not in the manifest file.
In Rails 6 there are two commented lines in application.js. Regardless of what rails version you're running just make sure you add them in:
const images = require.context('../images', true)
const imagePath = (name) => images(name, true)
Alternatively, you can force the images to be added to the manifest by moving your folder inside packs
, eg. packs/images
. The path would change though to media/images/your-file.png
.
For seeing if the path exists or not, I found it easier to just lookup it up from ruby directly:
Webpacker.manifest.send(:data).keys.grep /logo/
For accessing images handled by Sprockets, add this to your your_file_name.js.erb file:
<% helpers = ActionController::Base.helpers %>
const railsImagePath = "<%= helpers.image_path('your_image.png') %>"
My images are located in /app/assets/images
.
Firstly add app/assets
to resolved_paths: ['app/assets']
in webpacker.yml
And then you can use the image in your JS like so:
<img src='~images/logo.png' />
in CSS:
<style lang='sass'>
#app
background: url('~images/logo.png')
</style>
Place your images in
app/javascripts/images
Put following code in application.js
At TOP of the file.
// top of packs/application.js
const importAll = (r) => r.keys().map(r)
importAll(require.context('../images', false, /\.(png|jpe?g|svg)$/));
This will load all images from images folder and then it should be available in manifest for you to pick up using
asset_pack_path
In your erb
files, use like <%= asset_pack_path 'media/images/image_name.png' %>
-- Read this for more details https://github.com/rails/webpacker/issues/1839