簡體   English   中英

Symfony2 + Twig:嘗試從全局名稱空間調用函數“ replace”

[英]Symfony2 + Twig: Attempted to call function “replace” from the global namespace

我的應用程序中出現此錯誤,但我找不到失敗的地方:

嘗試從全局名稱空間調用函數“替換”。

這是Stacktrace:

[1] Symfony\Component\Debug\Exception\UndefinedFunctionException: Attempted to call function "replace" from the global namespace.
    at n/a
        in /var/www/html/reptooln_admin/app/cache/dev/twig/eb/76/c3cb3f071f775598b83974700b4a2523941a76b0f3cf8801d01d9210eae0.php line 318

現在在我的代碼中,我定義了這個Twig擴展:

services:
    app.twig.extension:
        class: AppBundle\Extension\AppTwigExtension
        tags:
            -  { name: twig.extension }

這是課程:

<?php

namespace AppBundle\Extension;

class AppTwigExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'var_dump'   => new \Twig_Filter_Function('var_dump'),
            'empty' => new \Twig_Filter_Function('empty', array($this, 'is_empty')),
            'isset' => new \Twig_Filter_Function('isset', array($this, 'is_set')),
            'isnull' => new \Twig_Filter_Function('isnull', array($this, 'is_null')),
            'ucfirst' => new \Twig_Filter_Function('ucfirst', array($this, 'uc_first')),
            'ucwords' => new \Twig_Filter_Function('ucwords', array($this, 'uc_words')),
            'count' => new \Twig_Filter_Function('count', array($this, 'co_unt')),
            'sizeof' => new \Twig_Filter_Function('sizeof', array($this, 'size_of')),
            'concat' => new \Twig_Filter_Function('concat', array($this, 'concat')),
            'in_array' => new \Twig_Filter_Function('in_array', array($this, 'inarray')),
            'array' => new \Twig_Filter_Function('array', array($this, 'array_')),
            'add_to_array' => new \Twig_Filter_Function('add_to_array', array($this, 'add_to_array')),
            'replace' => new \Twig_Filter_Function('replace', array($this, 'replace')),
            'htmlentitydecode' => new \Twig_Filter_Function('htmlentitydecode', array($this, 'htmlentitydecode')),
        );
    }

    public function replace($subject, $search, $replace)
    {
        return str_replace($search, $replace, $subject);
    }
    // functions goes here

    public function getName()
    {
        return 'app_twig_extension';
    }
}

怎么了? 我找到了這篇文章,但對我的情況沒有幫助

從該錯誤看來,您似乎已經注冊了一個名為replace的過濾器,但是您試圖將其作為函數調用。

因此,這應該已經可以工作了(但是我不認為這是您想要做的):

{{ my_variable|replace('something', 'with', 'this') }}

我認為您正在嘗試做的是:

{{ replace(my_variable, 'replace', 'this') }}

若要注冊函數,請在AppTwigExtension類中添加一個名為getFunctions的方法,然后將replace定義AppTwigExtension該類。 有關更多詳細信息,請參見文檔

暫無
暫無

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

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