我正在使用symfony 4.0和created a custom config file。我将此配置文件值设置为参数,以便我可以在控制器中获取它们。但我想将它们传递给twig。我怎么能这样做?可以直接在config.yml中分配应用程序配置,还是可以使用twig扩展名来实现?我找到了getGlobals()
,但这已被弃用。仍然使用枝条功能,但似乎不是一个好方法。
最好,谢谢!
AppExtension.php:
namespace AppBundle\DependencyInjection;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
class AppExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('config', $config);
}
}
?>
资源/配置/ app.yml:
app:
document_access:
payment:
bank_details:
account_owner: xxx
iban: Iban
bic: Bic
ConfigExtension.php
namespace AppBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ConfigExtension extends \Twig_Extension
{
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getFunctions(){
return array(
new \Twig_SimpleFunction('config', array($this, 'getConfig')),
);
}
public function getConfig()
{
return $this->container->getParameter('config');
}
}
答案 0 :(得分:0)
将所需的变量设置为环境变量和参数。
然后你可以将参数注入控制器或将变量注册为twig globals。
<强>控制器强>
class AngularController
{
protected $twig;
protected $accountOwner;
protected $iban;
protected $bic;
/**
* AngularController constructor.
* @param $accountOwner
* @param $iban
* @param $bic
*/
public function __construct(\Twig_Environment $twig, $accountOwner, $iban, $bic)
{
$this->twig=$twig;
$this->accountOwner = $accountOwner;
$this->iban = $iban;
$this->bic = $bic;
}
/**
* @Route("/uri", name="your_route")
*/
public function yourActionAction()
{
$data=["account_owner"=>$this->accountOwner, "iban"=>$this->iban, "bic"=>$this->bic];
$content=$this->twig->render('Bundle:Bundle:index.html.twig', $data);
$response=new Response($content);
return $response;
}
}
controller.angular:
class: DJABundle\Controller\AngularController
arguments:
- "@twig"
- %bank_account_owner%
- %bank_iban%
- %bank_bic%
Twig globals
# app/config
twig:
[...]
globals:
account_owner: %bank_account_owner%
iban: %bank_iban%
bic: "%bank_bic%"
控制器和全局变量的twig用法
Bank account owner: {{ account_owner }}
Bank account iban: {{ iban }}
Bank account bic: {{ bic }}