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

Point variable in the volt


$lang = $this->session->get("lang");
$name = "name_".$lang;
foreach($slide as $key => $val){
     echo $val->$name;
}

how to write $val->$name in the Volt

Thanks so much.



145.0k
Accepted
answer

Why not use translation component ? But for your question you can use function or filter:

$di->set('view', function () use ($di) {
    $view = new \Phalcon\Mvc\View\Simple();
    $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
    $compiler=$volt->getCompiler();
    $compiler->addFilter('attribute', function ($resolvedArgs, $exprArgs)
    {
        return vsprintf('%s->{%s}', explode(', ', $resolvedArgs));
    });
    $view->registerEngines([
        'volt' => $volt
    ]);
    return $view;
});

And then in view : {{ object|attribute(xyz) }}

$di->set('view', function () use ($di) {
    $view = new \Phalcon\Mvc\View\Simple();
    $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
    $compiler=$volt->getCompiler();
    $compiler->addFunction('attribute', function ($resolvedArgs, $exprArgs)
    {
        return vsprintf('%s->{%s}', explode(', ', $resolvedArgs));
    });
    $view->registerEngines([
        'volt' => $volt
    ]);
    return $view;
});

And then in view : {{ attribute(object,xyz) }}

i get $slide from DB and foreach it in the Volt. i don't know volt doesn't support.

Thank for your help

Twig for example don't support it too(you have use getAttribute).