phalcon : volt get value from array which key taken from variable

AzDesign picture AzDesign · Mar 25, 2014 · Viewed 12.5k times · Source

In phalcon templating engine volt (which is similar to twig) you can fetch all records by :

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

So, in my scenario, I'm building a crud template which will be used for different kind of models. What I wanted to achieve in this template is that every columns in this view are not hard-coded. So I store the columns I wanted to show into an array (defined in the controller, passed to the view) :

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

In the view, to make it display all columns :

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

Obviously, this will result in error, because there is no "col" in product.

Is there any solution or alternative for this ?

Answer

AzDesign picture AzDesign · Mar 27, 2014

While frustrated tinkering with volt extension, I found a simpler solution :

  1. Convert the model object into array. In the controller : $products->toArray()

  2. Simply, in the view, to display specific value of specific key from an array : {{ product[key] }}

Problem solved, though because it is now not in form of object, I can't access object property using dot like {{ product.some_field }}, instead {{ product['some_field'] }}.