我建議創建一個服務和一個樹枝擴展來通過你的模板來訪問它。
這樣,你只需要像做:
{{ product | priceByRole }}
這將「按角色價」訪問服務,處理安全邏輯。
服務:http://symfony.com/doc/current/book/service_container.html 寫的樹枝延伸:http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html
例嫩枝擴展:
<?php
namespace Acme\DemoBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PriceByRoleExtension extends \Twig_Extension implements ContainerAwareInterface
{
protected $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function getFilters()
{
return array(
'priceByRole' => new \Twig_Filter_Method($this, 'priceByRoleFilter'),
);
}
public function priceByRoleFilter(Item $entity)
{
$service = $this->container->get('my.price.service');
return $service->getPriceFromEntity($entity);
}
public function getName()
{
return 'acme_extension';
}
}
示例服務:
<?php
namespace Acme\DemoBundle\Service;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Acme\DemoBundle\Entity\Product;
class PriceService
{
protected $context;
public function setSecurityContext(SecurityContextInterface $context = null)
{
$this->context = $context;
}
public function getPriceFromEntity(Product $product)
{
if ($this->context->isGranted('ROLE_A'))
return $product->getWholesalePrice();
if ($this->context->isGranted('ROLE_B'))
return $product->getDetailingPrice();
if ($this->context->isGranted('ROLE_C'))
return $product->getPublicPrice();
throw new \Exception('No valid role for any price.');
}
}
@Alex喬伊斯的答案是比我好。我的解決方案更直接,但如果您需要此角色,請選中幾個模板,您應該選擇Service + Twig Extension解決方案。 –