Question

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 ?

Was it helpful?

Solution

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'] }}.

OTHER TIPS

You should use the readAttribute() function: http://forum.phalconphp.com/discussion/1231/volt-access-to-object-property-using-variable

{{ product.readAttribute(col) }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top