如何在 Twig 模板中渲染控制器返回的图像
How do I render a controller returned image in a Twig template
为了保护客户上传的图片,我将它们存储在 "app/data" 中,并使用以下控制器检索它们:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class AssetsController extends Controller {
...
public function serveProfilePictureAction() {
...
$response = new BinaryFileResponse($filePath);
$response->headers->set('Content-Type', 'image/' . $this->getImageMimeType($filePath));
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
return $response;
}
}
如果我使用路由调用控制器,控制器工作正常并提供图像。但是如何将图像嵌入到 Twig 模板中呢?我试过了
{{ render(controller('SecuredAssetsBundle:Assets:serveProfilePicture')) }}
但这没有任何作用。
谢谢!
您必须将其嵌入为图像标签,以便浏览器为您获取:
<img src="{{ path('serveProfilePictureRoute') }}" alt="Your profile picture" />
其中 serveProfilePictureRoute
是您为个人资料图片路线命名的任何内容。
为了保护客户上传的图片,我将它们存储在 "app/data" 中,并使用以下控制器检索它们:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class AssetsController extends Controller {
...
public function serveProfilePictureAction() {
...
$response = new BinaryFileResponse($filePath);
$response->headers->set('Content-Type', 'image/' . $this->getImageMimeType($filePath));
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
return $response;
}
}
如果我使用路由调用控制器,控制器工作正常并提供图像。但是如何将图像嵌入到 Twig 模板中呢?我试过了
{{ render(controller('SecuredAssetsBundle:Assets:serveProfilePicture')) }}
但这没有任何作用。
谢谢!
您必须将其嵌入为图像标签,以便浏览器为您获取:
<img src="{{ path('serveProfilePictureRoute') }}" alt="Your profile picture" />
其中 serveProfilePictureRoute
是您为个人资料图片路线命名的任何内容。