We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Widgets with Volt rendering

Hello,

Can I create widget with personal Volt template? I want to use it on several pages. This widget should render dynamic information.



98.9k

There are several approaches for accomplish this, I suggest you this approach:

Create a class for your widget:

class MyWidget extends Phalcon\DI\Injectable
{

    public function __construct()
    {
       //...
    }

    public function execute()
    {
       //...
    }

    public function getContent()
    {
        //...
    }
}

Create a widget manager:

class MyWidgetsManager
{
    public static function get($widgetClass, $parameters=null)
    {
        return new $widgetClass($parameters);        
    }
}

Add a function in volt:

$compiler = $volt->getCompiler();

$compiler->addFunction('render_widget', function($resolvedArgs) {    
    return 'MyWidgetsManager::get(' . $resolvedArgs . ')->getContent()';    
});

Usage:

{{ render_widget('MyWidget', [$param1, $param2]) }}

OK, but what about Volt instance in DI container? Can I use it to compile this widget, or I should create a new instance for it?



98.9k

Yes, the Volt instance in the DI is where the function must be added.

Can you add this function to the Volt?



98.9k

Support it out of the box?

I think it will be great :-)



43.9k

Hi, -1 : keep phalcon simple +1 : phalcon should give short and easily accessible solutions for this common task (as for "scopes", see the post related to this feature request)

this was really a 2cts contribution ! sorry.