emzet
emzet

Reputation: 58

ruby on rails 6 - referencing images dynamically in java script

I am trying to implement chessboard.js and chess.js (https://chessboardjs.com/examples#2030) in the ruby on rails 6 framework and have a problem with rendering images of pieces on the chessboards (images of pieces are attached to the libraries in separate files). I added both java scripts libraries using webpacker. I was trying to place the images in various places of the project but neither worked (for example ..\img\chesspieces\wikipedia)

I am able to render single picture separately outside of chessboard but don't know how to reference the images dynamically in the java script so that they would be displayed on the chessboard in ruby on rails 6 framework.

How should I build the path to the pictures in the below java script in the ruby on rails 6 framework? (the line: return 'img/chesspieces/wikipedia/' + piece + '.png' in the below code)

My index.html.erb file:

<div id="board1" style="width: 400px"></div>
   
  <script> 
  function pieceTheme (piece) {
    // wikipedia theme for white pieces
    if (piece.search(/w/) !== -1) {
      return "img/chesspieces/wikipedia/" + piece + '.png'
    }
    // alpha theme for black pieces
    return "img/chesspieces/wikipedia/" + piece + '.png'
    }

  var config = {
    pieceTheme: pieceTheme,
    position: 'start'
  }
  var board1 = Chessboard('board1', config) 
  
  </script>
    

The Error example: wP.png:1 GET http://localhost:3000/img/chesspieces/wikipedia/bQ.png 404 (Not Found)

I was only able to render a single picture by adding to application.js

// import all image files in a folder:
const images = require.context('../images', true)
const imagePath = (name) => images(name, true)

and then by adding to index.html.erb

  <%= image_pack_tag 'bB.png' %>

UPDATE: if I source the images from the https://chessboardjs.com/img/chesspieces/wikipedia/ it is working fine, but I don't think it is a proper way to reference those pictures. I would like to reference them from the project files.

return "https://chessboardjs.com/img/chesspieces/wikipedia/" + piece + '.png'

Upvotes: -1

Views: 93

Answers (1)

Maxpan
Maxpan

Reputation: 559

Try to Change the code

const images = require.context('../images', true)

to

const images = require.context('./images', true)

Upvotes: 0

Related Questions