FOSJsRoutingBundle
repository·master·Indexed 23 days ago
https://github.com/friendsofsymfony/fosjsroutingbundleA 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.
What's inside FOSJsRoutingBundle
- FOSJsRoutingBundle allows you to expose your Symfony routing configuration to your JavaScript code. This enables you to generate URLs with specific parameters directly in JavaScript, mimicking the behavior of the Symfony Router component used in PHP.
Expose routes to JavaScript
masterBy 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@Routeannotation.Global Configuration: You can define a list of routes to expose in
app/config/config.ymlusing theroutes_to_exposekey. 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_1to 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) { // ... }Register FOSJsRoutingBundle routes
masterLoad the bundle's routing definition in your application configuration (e.g., in
config/routes.yaml) using the following YAML configuration:fos_js_routing: resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.php"Enable FOSJsRoutingBundle in Symfony
masterIf not automatically enabled by Symfony Flex, add the bundle to your
config/bundles.phpfile to register it within your application.<?php // config/bundles.php // ... return [ // ... FOS\JsRoutingBundle\FOSJsRoutingBundle::class => ['all' => true], // ... ];Install FOSJsRoutingBundle via Composer
masterTo install the latest stable version of the bundle, run the following command in your project directory. Note that if you are using Symfony Flex, the subsequent configuration steps may be handled automatically.
composer require friendsofsymfony/jsrouting-bundlePublish FOSJsRoutingBundle assets
masterExecute the Symfony asset installation command to publish the required bundle assets to your
publicdirectory:php bin/console assets:install --symlink publicDump route information to a static file with fos:js-routing:dump
masterUse the
fos:js-routing:dumpcommand 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:dumpIntegration
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_HOSTenvironment variable to your hostname including the port (e.g.,localhost:8443). - Alternatively, use the
setHostandsetPortmethods on theRouterobject at runtime.
Using JMSI18nRoutingBundle
If you use
JMSI18nRoutingBundle, you must run the command for each locale using the--localeand--targetparameters:# Example for a specific locale php bin/console fos:js-routing:dump --locale=en --target=js/fos_js_routes_en.jsNote: 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- Set the
Setup FOSJsRoutingBundle with Webpack and Encore
masterIf you use Webpack and Encore, use the included Webpack plugin. The plugin automatically triggers the
fos:js-routing:dumpcommand when routes change during thebuildorwatchprocesses.To use it, add the plugin to your Encore configuration and import
Routingfromfos-routerin 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.jsonfile and suppress automatic recompilation by passing options to the constructor:target: The path to your dumpedroutes.json.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.jsonconst FosRouting = require('fos-router/webpack/FosRouting'); //... Encore .addPlugin(new FosRouting())Install FOSJsRoutingBundle npm package for Webpack
masterIf your project uses Webpack, you must install the bundle's resources locally as a development dependency using
yarn:yarn add -D ./vendor/friendsofsymfony/jsrouting-bundle/Resources/Setup FOSJsRoutingBundle without Webpack
masterIf 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.jsasset and a script tag that calls thefos_js_routing_jsroute with thefos.Router.setDatacallback.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>Configure the Router service
masterBy default, the bundle exports routes from the standard Symfony
routerservice. If you have a custom router service, you can configure the bundle to use it inapp/config/config.yml:# app/config/config.yml fos_js_routing: router: my_router_servicefos_js_routing: router: my_router_serviceHow route name resolution works
masterWhen calling
getRoute(name)(internally used bygenerate), the router attempts to find the route by checking several name variations to support internationalization and prefixes. It checks the following patterns in order:{prefix}{name}{name}.{locale}{prefix}{name}.{locale}{name}
If none of these variations exist in the provided routing data, the router throws an error:
The route "{name}" does not exist.