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

Volt function to return html

Hey Guys,

I'm wondering what is the correct way to write a function that extends volt that returns html.

I've tried:

$compiler->addFunction( "latestFeed", function ($resolvedArgs, $exprArgs) use ($compiler) { return "<div>Yo</div>"; });

But it always errors with a parser error: Parse error: syntax error, unexpected '<'

Cheers, Ben

Please note the quotes:

// Filter / Modifier
$compiler->addFilter('prettyDate', function($resolvedArgs, $exprArgs){
    return 'Helpers\Volt::prettyDate(' . $resolvedArgs . ')';
});

// Function
$compiler->addFunction('getUpload', function($resolvedArgs, $exprArgs){
    return 'Helpers\Common::getUpload(' . $resolvedArgs . ')';
});


3.4k

You could also add your own class holding methods instead of using anonymous functions.

services.php

$objDi->set('StringFunctions', function() {
    return new \StringFunctions();
});

StringFunctions.php

class StringFunctions extends \Phalcon\Tag
{
      public function foo($text) 
      {
            return "<div>". htmlspecialchars($text) ."</div>";
      }
}

*controller.php

//.....
public function somethingAction()
{
       $this->view->someText = "Yo";
}
//....

*.volt

{{ StringFunctions.foo(someText) }}