簡體   English   中英

如何將樹枝過濾器注冊到 Symfony 4?

[英]How to register twig filter into Symfony 4?

我在 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 = 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
        ];
    }
}

旁注getName方法現已過時,可以刪除,因為它已被棄用並且不再在代碼中使用

來源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM