symfony模板渲染:
①常规方式
// src/Controller/ProductController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
public function index(): Response
{
// ...
// the `render()` method returns a `Response` object with the
// contents created by the template
return $this->render('product/index.html.twig', [
'category' => '...',
'promotions' => ['...', '...'],
]);
// the `renderView()` method only returns the contents created by the
// template, so you can use those contents later in a `Response` object
$contents = $this->renderView('product/index.html.twig', [
'category' => '...',
'promotions' => ['...', '...'],
]);
return new Response($contents);
//或者直接 render
return $this->render('product/index.html.twig', [
'pagination' => $pagination,
'query' => $request->query->all(),
]);
}
}
②v5.4版本以后可以通过Annotation方式,虽然官网说是v6.2以后才行
// src/Controller/ProductController.php
namespace App\Controller;
use Symfony\Bridge\Twig\Attribute\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
#[Template('product/index.html.twig')] //Annotation方式
public function index()
{
// ...
// when using the #[Template()] attribute, you only need to return
// an array with the parameters to pass to the template (the attribute
// is the one which will create and return the Response object).
return [
'category' => '...',
'promotions' => ['...', '...'],
];
}
}
③在非控制器(比如 service 里面)
// src/Service/SomeService.php
namespace App\Service;
use Twig\Environment;//注意这个twig的环境变量
class SomeService
{
public function __construct(
private Environment $twig,
) {
}
public function someMethod()
{
// ...
$htmlContents = $this->twig->render('product/index.html.twig', [
'category' => '...',
'promotions' => ['...', '...'],
]);
}
}
④直接在 config/routes.yaml 渲染模板,虽然模板通常在控制器和服务中呈现,但你可以直接从路由定义中呈现不需要任何变量的静态页面。使用Symfony提供的特殊TemplateController:
acme_privacy:
path: /admin/test //路由
controller: Symfony\Bundle\FrameworkBundle\Controller\TemplateController //这个控制器是symfony自带的,不许用我们处理
defaults:
# the path of the template to render
template: 'admin/test.html.twig' //只需要一个静态页面即可
# the response status code (default: 200)
statusCode: 200
# special options defined by Symfony to set the page cache
maxAge: 86400
sharedAge: 86400
# whether or not caching should apply for client caches only
private: true
# optionally you can define some arguments passed to the template
context:
site_name: 'ACME'
theme: 'dark'
检查所有模板:$ php bin/console lint:twig
展示模板信息:$ php bin/console debug:twig
