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

Recursion in addFunction()

As I have gone through the documentation provided by Phalcon for Volt Template Engine, I found addFunction() to add custom function in Volt Compiler to customize data. But regarding n-level hierarchical menu / catalog, I need recursion in addFunction() which I am unable to make it work. Please guide me a solution for this.

That's a pretty generic question with very little detail:

Why do you need recursion? What have you tried so far? What does your code look like?

I have done this much so far . .

Controller:

$compiler->addFunction( 'menu', function ($resolvedArgs, $exprArgs) { return 'Menu::menu(' . $resolvedArgs . ')'; } );

Library:

class Menu { public static function menu($data) { if (empty($data)) { return ''; }

  $out = '<ul>';
  foreach ($data as $name => $children) {
      $out .= '<li>' . $name . self::menu($children) . '</li>';
    }
  $out .= '</ul>';
  return $out;

} }

Volt:

{{menu(menus)}}

Output:

<ul><li>a<ul><li>a1<ul><li>a11</li><li>a12</li><li>a13</li></ul></li></ul></li><li>b</li></ul>

The output is thus generated. But this way, I have to work on library file, but not a template file, each time when I have to rebuild the html structure. I am not quite satisfied with the coding practice as the tags are processed by the library here. So I want to implement a practice of building total html structures in volt template files only rather than other. Please guide me through this.