Phalcon: volt get value from an array that is selected from a variable

In phalcon templating engine volt (which looks like a twig) you can get all the entries:

{% for product in products %}
    Name: {{ product.name }}
    Description: {{ product.description }}
    price: {{ product.price}}
{% endfor  %}

So, in my scenario, I am creating a crud template that will be used for different models. What I wanted to achieve in this template is that all the columns in this view are not hardcoded. Therefore, I store the columns that I wanted to show in an array (defined in the controller, passed to the view):

$cols = ['name','description','price']

In a view to display all columns:

{% for product in products %}
   {% for col in cols %}
       {{ col }}: {{ product.col }}
   {% endfor  %}
{% endfor  %}

Obviously, this will result in an error because the product does not have a col.

Is there any solution or alternative for this?

+4
source share
3

, :

  • . : $products->toArray()

  • : {{ product[key] }}

, , , , {{ product.some_field }}, {{ product['some_field'] }}.

+2
+1

:

app/config/service.php:

$di->set('volt', function($view, $di) {
    $volt = new VoltEngine($view, $di);
    $volt->setOptions(array(
        'compiledPath' => APP_PATH . 'cache/volt/'
    ));
    $compiler = $volt->getCompiler();
    // Add this filter
    $compiler->addFilter('getAttribute', function ($resolvedArgs, $exprArgs) {
        return vsprintf('%s->{%s}', explode(', ', $resolvedArgs));
    });

    return $volt;
}, true);

volt:

product|getAttribute(key)
0

Source: https://habr.com/ru/post/1533352/


All Articles