如何在Controller中生成ESI/Hinclude Fragment URL(无需Twig)
在Symfony控制器中生成Fragment URL(ESI/Hinclude)
要在控制器中生成Twig里render_esi/render_hinclude对应的Fragment URL,直接用$router->generate()无法得到目标格式,需要使用Symfony内置的FragmentUriGeneratorInterface服务,它专门负责生成带签名验证的Fragment路径,和你提供的示例URL格式完全一致。
实现步骤:
注入FragmentUriGenerator服务
通过构造函数将服务注入到控制器中:use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpKernel\Fragment\FragmentUriGeneratorInterface; use App\Controller\ProductCrudController; class YourController extends AbstractController { private $fragmentUriGenerator; public function __construct(FragmentUriGeneratorInterface $fragmentUriGenerator) { $this->fragmentUriGenerator = $fragmentUriGenerator; } // ... 你的控制器方法 }生成Fragment URL
在控制器方法中,传入目标控制器引用、参数和渲染策略(esi或hinclude)即可生成对应URL:public function yourAction() { // 目标控制器(类名::方法名格式) $targetController = [ProductCrudController::class, 'jobListAction']; // 需传递的参数集合 $params = [ 'jobId' => 206, '_sonata_admin' => 'admin.job.product', 'pathInfo' => '/job/206/edit', '_format' => 'html', '_locale' => 'pl', ]; // 生成ESI类型的Fragment URL $esiUrl = $this->fragmentUriGenerator->generate($targetController, $params, 'esi'); // 生成Hinclude类型的Fragment URL $hincludeUrl = $this->fragmentUriGenerator->generate($targetController, $params, 'hinclude'); // 后续可将URL用于响应输出或传递给模板 return $this->json([ 'esi_fragment_url' => $esiUrl, 'hinclude_fragment_url' => $hincludeUrl, ]); }
关键说明:
- 生成的URL会自动包含
_hash签名参数,用于Symfony Fragment系统的安全验证,和你提供的示例格式完全匹配 - 若使用Symfony 4及以下版本,也可通过
$this->get('fragment.uri_generator')直接获取服务(但更推荐依赖注入方式)
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

