2

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 + "\"/>";
mrsharko
  • 285
  • 2
  • 9
  • 22
  • @DarkBee yes and i tested it using helloworld code before adding the code above – mrsharko Apr 19 '17 at 20:20
  • 1
    You have to consider twig as being like PHP. It is rendered server side. Here you are trying to have a different asset based on a JS variable ```pieceFileName```, which is client side. So what your are looking at is impossible this way. You should maybe rather head to an AJAX solution. See the related question: http://stackoverflow.com/q/13840429/2123530 – β.εηοιτ.βε Apr 19 '17 at 20:59
  • @b.enoit.be you are right so i need to add the asset line on the twig file then i pass it to the javascript file that what you mean ? – mrsharko Apr 20 '17 at 06:23

1 Answers1

3

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.

kero
  • 10,647
  • 5
  • 41
  • 51