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

Accessing object properties whose name contain a hyphen in volt

I have an array with the following structure:

array(
    'profile' => object(
        'first-name' => 'Matthew'
    ),
    'contact' => object(
        'tel' => 0
    )
)

How can I access that 'first-name' attribute using Volt? In PHP, whilst looping I would do the following:

$row['profile']->{'first-name'}

However that doesn't work in Volt. I have the following so far:

{% set profile = row['profile'] %}
{{ profile.{'first-name'} }}

But that is compiling as follows, changing curly braces to square:

<?=$profile->['first-name']?>
edited Nov '18

You could add a filter to the volt compiler:

$volt->getCompiler()->addFilter('getAttribute', function ($resolvedArgs, $exprArgs) use ($di)
{
    return vsprintf('%s->{%s}', explode(', ', $resolvedArgs));
});
 {{ obj|getAttribute('hyphen-key') }}

would compile as

 <?php echo $obj->{'hyphen-key'}; ?>

Solution by @Yvan from this thread:

https://forum.phalcon.io/discussion/1231/volt-access-to-object-property-using-variable

I actually added the built-in get_object_vars() function to my volt compiler, so I can then add this to my view and treat it as an array:

{% set profile = get_object_vars(row['profile']) %}
{{ profile['first-name'] }}