New in Symfony 4.2: addLink() shortcut
November 5, 2018 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Kévin Dunglas
in #28875.
The WebLink component introduced in Symfony 3.3 provides tools to manage the
Link
HTTP header needed for Web Linking when using HTTP/2 Server Push
as well as Resource Hints. In practice, it can improve the performance of
your web apps dramatically.
In order to simplify its usage, in Symfony 4.2 we've added a new addLink()
shortcut to AbstractController
. For example, this is how you can preload a
CSS file (to send it before the browser requests it):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// src/Controller/BlogController.php
namespace App\Controller;
use Fig\Link\GenericLinkProvider;
use Fig\Link\Link;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class BlogController extends AbstractController
{
public function index(Request $request)
{
// BEFORE
$linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
$request->attributes->set('_links', $linkProvider->withLink(new Link('preload', '/app.css')));
// AFTER
$this->addLink($request, new Link('preload', '/app.css'));
return $this->render('...');
}
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.