Search code examples
javascriptimagesymfonytwigassets

symfony : using asset images with javascript?


in flat php code i can just write this line like that and I get the images I want

imageString = "<image src=\"" + pieceFileName + "\" class=\"Piece clickElement " + rankName + " " + fileName + "\"/>";

but with javascript symfony how ?

I tried to write this code like that but it did't work

imageString = "<img src=\"""{{ asset(' \""+ pieceFileName +"\" ')}}""\" class=\"Piece clickElement " + rankName + " " + fileName + "\"/>";

the full code

function AddGUIPiece(sq,pce) {  
    var rank = RanksBrd[sq];
    var file = FilesBrd[sq];
    var rankName = "rank" + (rank + 1); 
    var fileName = "file" + (file + 1); 
    pieceFileName = "images/" + SideChar[PieceCol[pce]] + PceChar[pce].toUpperCase() + ".png";
    imageString = "<image src=\"" + pieceFileName + "\" class=\"Piece clickElement " + rankName + " " + fileName + "\"/>";

Solution

  • Twig, like PHP, will run on the first render/call to server. So it cannot be combined with dynamic parts of code like you did.

    However, if all these images are in the same folder, why not just save the path to that?

    <script>
    var guiPiecePre = "{{ asset('images') }}";
    </script>
    

    Once you have defined that, concatenate to this string for the proper path like so

    pieceFileName = guiPiecePre + SideChar[PieceCol[pce]] + PceChar[pce].toUpperCase() + ".png";
    

    The key is, that guiPiecePre will have a static value (you can even see it in the rendered HTML if you inspect the source) and the dynamic part is appended when needed via JS.