【问题标题】:How can I set own Tag class in Volt (Phalcon)如何在 Volt (Phalcon) 中设置自己的标签类
【发布时间】:2013-08-07 23:38:54
【问题描述】:

我想重新声明并添加一些方法到 helper Tag。

class MyTags extends \Phalcon\Tag
{
    public static function mytag($params)
    {
       <...>
    }
}

在 services.php 中

$di->set('tag', function() {
    return new MyTags();
};

但它只适用于 PHP 引擎,不适用于 Volt。

{{ mytag() }}

返回

Undefined function 'mytag'

【问题讨论】:

    标签: php phalcon volt


    【解决方案1】:

    首先:不要使用tag 作为你的服务名称,因为它已经被 Phalcon 的 Tag 对象使用了。其次,您可以使用类中的静态方法。

    下面是myTag 的工作示例,使用我的应用程序中的配置并为您的示例更改名称。

    $di->set(
    'view',
    function () use ($config) {
        $view = new View();
        $view->setViewsDir($config->application->viewsDir);
        $view->registerEngines(
            array(
                '.volt' => function ($view, $di) use ($config) {
    
                    $volt = new VoltEngine($view, $di);
                    $volt->setOptions(
                        array(
                            'compiledPath' => $config->application->cacheDir,
                            'compiledSeparator' => '_',
                            'compileAlways' => false
                        )
                    );
                    $compiler = $volt->getCompiler();
    
                    // add a function
                    $compiler->addFunction(
                        'myTag',
                        function ($resolvedArgs, $exprArgs) {
                            return 'MyTags::mytag(' . $resolvedArgs . ')';
                        }
                    );
    
                    // or filter
                    $compiler->addFilter(
                        'myFilter',
                        function ($resolvedArgs, $exprArgs) {
                            return 'MyTags::mytag(' . $resolvedArgs . ')';
                        }
                    );
    
                    return $volt;
                }
            )
            );
    
            return $view;
        },
        true
    );
    

    然后您可以在伏特视图中使用您的myTag() 函数。

    但如果你想使用对象,那么不要使用静态方法:

    class MyTags extends \Phalcon\Tag
    {
        /**
         * Look no static keyword here
         */
        public function mytag($params)
        {
           <...>
        }
    }
    

    在服务中使用对象:

    $di->set('mahTag', function() {
        return new MyTags();
    };
    

    然后输入电压:

    {{ mahTag.mytag() }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多