Search code examples
javascripttwigassets

Javascript variable in a twig asset


I would like to use a document variable in a twig asset like this:

var imgName="HelloWorld.png";
document.getElementById("myImgTag").src="url({{asset( imgName) }})";

I know this is not working. Is there any manner to pass imgName in the asset field in this spirit?

Thanks by advance.


Solution

  • Make an asset directory:

    like this in the template

    <script>
        var assetsDir = "{{ asset('assets/') }}"
    </script>
    

    then in javascript use it like this:

    var imgName="HelloWorld.png"; 
    

    document.getElementById("myImgTag").src= assetDir + '/' + imgName