That's easy if you extend twig.
First, create a class that will contain the extension:
<?php
namespace AcmeDemoBundleTwigExtension;
use SymfonyComponentDependencyInjectionContainerInterface;
use Twig_Extension;
class VarsExtension extends Twig_Extension
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getName()
{
return 'some.extension';
}
public function getFilters() {
return array(
'json_decode' => new Twig_Filter_Method($this, 'jsonDecode'),
);
}
public function jsonDecode($str) {
return json_decode($str);
}
}
Then, register that class in your Services.xml
file:
<service id="some_id" class="AcmeDemoBundleTwigExtensionVarsExtension">
<tag name="twig.extension" />
<argument type="service" id="service_container" />
</service>
Then, use it on your twig templates:
{% set obj = form_label(category) | json_decode %}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…