Search code examples
javascriptphpsymfonyasseticsymfony-routing

Routing static urls in javascript files in symfony


I have some javascript files in my Symfonyt2 project that load some reources dynamically from the javascript file.
for example:

$('.records_list').DataTable({
    "language": {
        "url": "../shared/js/datatables.persian.json"
    }
});

the url ../shared/js/datatables.persian.json works in pages with url like /test but in pages with url ike /test2/action it fails.
How can i fix this?
Is there a tool like cssrewrite filter for assetic?
or can I make routes for such urls?


Solution

  • If you do not have too many cases like this, you can store your file path with twig in a hidden div for example :

    <div id="file-store" style="display:none;" data-value="{{ asset('shared/js/persian.json') }}"></div>
    

    And retrieve it in js :

    var sharedFile = $('#file-store').attr('data-value');
    $('.records_list').DataTable({
        "language": {
            "url": sharedFile
        }
    });
    

    If you have a lot of cases like this, then you can make use of the FOSJsRoutingBundle :

    https://github.com/FriendsOfSymfony/FOSJsRoutingBundle