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 Functions

Stupid question. New here just trying to learn.

I figure out the basics but for the good of me I can not figure out in what file i have to put the volt functions in.

All I am trying to do is limit the escape characters.

    <h4><a href="https://somesite.com/video/{{ title.url }}">{{ title.text }}</a></h4>

..and need maxlength 10 characters for the variables {{ title.text }} (not to be confused with font sizes)

Is there a simpler way to do this in volt. I know in php all I would do is this. substr($text,0,10);

This is what I have. I don't know where to put this.

    $compiler->addFunction('strlen', 
    function($resolvedArgs, $exprArgs) use ($compiler) {

    $string= $compiler->expression($exprArgs[0]['expr']);

    $secondArgument = $compiler->expression($exprArgs[1]['expr']);

    return 'substr(' . $string . ', 0 ,' . $secondArgument . ')';
    });

I figure this will go in my index.volt.

    <a href="https://url../{{ title.url }}">{{ strlen(title.text, 10) }}</a>


10.5k
Accepted
answer

You should add your compiler to your volt engine in your project 's bootstrap file (where you've initilized your view)

$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);

$compiler = $volt->getCompiler();

$compiler->addFunction('strlen', function($resolvedArgs, $exprArgs) use ($compiler) {
    $string= $compiler->expression($exprArgs[0]['expr']);
    $secondArgument = $compiler->expression($exprArgs[1]['expr']);
    return 'substr(' . $string . ', 0 ,' . $secondArgument . ')';
});

$view = new Phalcon\Mvc\View();
$view->registerEngines(array(
    ".volt" => $volt
));
$di->set('view', $view);

Check the documentation here