FOSJSRoutingBundle in symfony

http://symfony.com/logos/symfony_black_01.png?v=4

When developing the JavaScript calls, developers can often face a problem with dynamically changing routing. Sometimes during the refactoring, some methods change the URL. Usually, even switching to the development mode can slightly change the URL by prefixing it with /app_dev.php/. To avoid complex URL changes, it is recommended to install and configure this bundle. It will allow you to expose the selected routings to JavaScript, and then use JavaScript methods to generate the URLs.

This bundle does not require configuration, but it needs to be correctly placed (by executing the assets:install command) and it needs to be added to the javascripts section and the routing section. First, add the following to app/config/routing.yml at the end:

fos_js_routing:
    resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml"

Next, issue the following command:

$ php app/console assets:install --symlink web/

Then, modify the app/Resources/views/base.html.twig file’s javascripts block:

{% block javascripts %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="{{%20asset('bundles/fosjsrouting/js/router.js')%20}}"></script>
    <script src="{{%20path('fos_js_routing_js',%20{%20'callback':%20'fos.Router.setData'%20})%20}}"></script>

    {% javascripts
        'js/vendor/semantic-ui/semantic.min.js'
        'js/dev/app.js'
        output='/js/app.js'
    %}
        <script src="{{%20asset_url%20}}"></script>
    {% endjavascripts %}
{% endblock %}

In the preceding code, we have added two new JavaScript calls. This needs to be added as early as possible, as it will expose the Routing object and the Routing.generate() method with the same parameters as Twig’s path() function. However, note that FOSJSRoutingBundle only generates the routing specifically exposed to JS. We will handle this later when we add our API controller.

Recommended :  10 packages to easily deal with eloquent in laravel

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares