我有一个简单的问题:
我在项目中使用了许多不同的元素。它们必须是可编辑的,所以我将它们分组并将它们包含为这样的模板:
{% include '::Fields/special.html.twig' with {'avg': 'avgvalue','class':'test','value':'myValue'} %}
是否有可能为此创建快捷方式功能,例如:
{{ special(fieldvalues) }}
如果是的话,我该怎么做?
答案 0 :(得分:1)
创建twig function
,如:
<?php
// src\BW\MainBundle\Twig\BWExtension.php
namespace BW\MainBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BWExtension extends \Twig_Extension
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getFunctions() {
return array(
new \Twig_SimpleFunction('special', array($this, 'specialFunction')),
);
}
public function specialFunction($fieldvalues) {
// handle of field values
return $this->container->get('templating')->render('BWMainBundle:Main:test.html.twig'); // return string of rendered twig template
}
}
然后将其定义为服务:
# src\BW\MainBundle\Resources\config\services.yml
services:
bw_main.twig.bw_extension:
class: BW\MainBundle\Twig\BWExtension
arguments: ["@service_container"]
tags:
- { name: twig.extension }