我在Symfony 4中使用自定义树枝扩展名注册时遇到问题。我有创建扩展名,可以帮助我解码json数据,但是它不起作用。当我想使用json_decode过滤器时显示此消息。错误信息
我的自定义树枝过滤器的代码:
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getName() {
return 'Json Decode';
}
public function getFunctions()
{
return [
new TwigFilter('json_decode', [$this, 'json_decode']),
];
}
public function json_decode($input, $assoc = false) {
return json_decode($input,$assoc);
}
}
?>
这是一个twig_exension.yaml
services:
_defaults:
public: false
autowire: true
autoconfigure: true
# Uncomment any lines below to activate that Twig extension
#Twig\Extensions\ArrayExtension: null
#Twig\Extensions\DateExtension: null
Twig\Extensions\IntlExtension: null
Twig\Extensions\TextExtension: null
App\Twig\AppExtension: null
这是我的树枝文件中返回和错误的行
{% set commande = render(controller('App\\Controller\\StoreController::getProduitsCommandes')) | json_decode %}
这是StoreController.php中的Response返回
$response = new Response(json_encode(["produits"=>$produitsArray,"total_ht"=>$total_ht,"tva"=>$tva,"nbre_produits"=>$nbre_produits]));
$response->headers->set('Content-Type', 'application/json');
return $response;
当我输入php bin / console debug时:twig --filter = json_decode调试器返回此结果
---------
* json_decode(input, assoc = false)
谢谢您的关注如果有人可以解决方案将对我有所帮助
由于错误状态,filter
无法找到。这是由于您试图将您filter
的函数注册为函数,getFilters
而是将注册移至方法。同样,链接现有功能也是完全可行的
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('json_decode', 'json_decode'), //just chain to existing PHP function
];
}
}
sidenote该方法getName
现在已过时,可以删除,因为它已被弃用并且在代码中不再使用
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句