FOSJsRoutingBundle

repository·master·Indexed 23 days ago

https://github.com/friendsofsymfony/fosjsroutingbundle

A Symfony bundle that enables JavaScript applications to access Symfony's routing configuration to generate URLs dynamically on the client side. It provides the fos-router package (v2.5.0) and CLI tools like fos:js-routing:dump for exporting routes to JS or JSON files and fos:js-routing:debug for inspecting exposed routes.

Tokens
3.3K
Snippets
13
Records
22
Agent score
81%

What's inside FOSJsRoutingBundle

  1. Expose routes to JavaScript

    master

    By default, routes are not available to the JavaScript router. You must explicitly expose them.

    Using Attributes (PHP): Add options: ['expose' => true] to your #[Route] attribute.

    Using YAML: Add options: { expose: true } to your route definition.

    Using Annotations (Deprecated): Add options={"expose"=true} to your @Route annotation.

    Global Configuration: You can define a list of routes to expose in app/config/config.yml using the routes_to_expose key. This supports regular expression patterns.

    Internationalization (i18n): If using JMSI18nRoutingBundle, ensure your exposed routes match the locale-prefixed names (e.g., en__RG__route_name) or use a regex pattern like [a-z]{2}__RG__route_1 to match all locales.

    Preventing Exposure: To ensure a route is NOT exposed, set options: { expose: false } in your routing configuration.

    #[Route(path: '/foo/{id}/bar', name: 'my_route_to_expose', options: ['expose' => true])]
    public function indexAction($foo) {
        // ...
    }
  2. Dump route information to a static file with fos:js-routing:dump

    master

    Use the fos:js-routing:dump command to export route information into a static JavaScript file. This is useful for avoiding controller-generated JavaScript and allows you to include routes in your asset pipeline (like Assetic) or serve them as a standard file.

    Usage

    Run the command via the Symfony console:

    php bin/console fos:js-routing:dump

    Integration

    Instead of using the dynamic Twig helper:

    <script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>

    You can now include the generated file directly in your HTML:

    <script src="/js/fos_js_routes.js"></script>

    Or include it within an Assetic block:

    {% javascripts filter='?yui_js'
        'bundles/fosjsrouting/js/router.js'
        'js/fos_js_routes.js'
    %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}

    Important Considerations

    Host and Port Configuration

    Because the console command is unaware of the host/port used during a web request, generated URLs might be incorrect. To fix this:

    • Set the HTTP_HOST environment variable to your hostname including the port (e.g., localhost:8443).
    • Alternatively, use the setHost and setPort methods on the Router object at runtime.

    Using JMSI18nRoutingBundle

    If you use JMSI18nRoutingBundle, you must run the command for each locale using the --locale and --target parameters:

    # Example for a specific locale
    php bin/console fos:js-routing:dump --locale=en --target=js/fos_js_routes_en.js

    Note: You can only load one locale's dump at a time in your HTML, as subsequent loads will overwrite the previous data.

    $ php bin/console fos:js-routing:dump
  3. Setup FOSJsRoutingBundle with Webpack and Encore

    master

    If you use Webpack and Encore, use the included Webpack plugin. The plugin automatically triggers the fos:js-routing:dump command when routes change during the build or watch processes.

    To use it, add the plugin to your Encore configuration and import Routing from fos-router in your JavaScript/TypeScript code.

    Configuring for CI/Docker (Static Routes): In environments without PHP (like Docker build layers), you can configure the plugin to use a static routes.json file and suppress automatic recompilation by passing options to the constructor:

    1. target: The path to your dumped routes.json.
    2. false: A boolean to suppress automatic recompilation.

    Manual Dump Command: You can manually export routes to a JSON file using the CLI: bin/console fos:js-routing:dump --format=json --target=assets/js/routes.json

    const FosRouting = require('fos-router/webpack/FosRouting');
    //...
    Encore
      .addPlugin(new FosRouting())
  4. Setup FOSJsRoutingBundle without Webpack

    master

    If you are not using a module bundler like Webpack, you must manually include the router JavaScript files and the data script in your layout.

    With Twig: Include the router.min.js asset and a script tag that calls the fos_js_routing_js route with the fos.Router.setData callback.

    With PHP: Use the asset manager and router service to generate the equivalent script tags.

    If you are not using Twig, ensure both JavaScript files are loaded at some point in your web page.

    <script src="{{ asset('bundles/fosjsrouting/js/router.min.js') }}"></script>
    <script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>
  5. How route name resolution works

    master

    When calling getRoute(name) (internally used by generate), the router attempts to find the route by checking several name variations to support internationalization and prefixes. It checks the following patterns in order:

    1. {prefix}{name}
    2. {name}.{locale}
    3. {prefix}{name}.{locale}
    4. {name}

    If none of these variations exist in the provided routing data, the router throws an error: The route "{name}" does not exist.