twigphp / Twig

Twig, the flexible, fast, and secure template language for PHP
https://twig.symfony.com/
BSD 3-Clause "New" or "Revised" License
8.15k stars 1.24k forks source link

Using array values as keys in another array #739

Closed Sprocket closed 12 years ago

Sprocket commented 12 years ago

I'm passing two arrays to my twig template, effectively this:

$categories = array( '1'=>'fruit', '2'=>'cars'); $products = array( array('name' => 'apple', 'category'=>'1') );

How do I get twig to echo the appropriate value for the category that the products belongs? I was hoping something like this:

{% for product in products %} {{ categories[product.category] }} {% endfor %}

I appreciate this isn't perhaps the best place to post this but everything I've found elsewhere is confused and there doesn't seem to be another Twig forum. Thanks for your time.

fabpot commented 12 years ago

You should use the mailing-list for your questions (https://groups.google.com/group/twig-users).

I've just tried your example and indeed, it works as expected. Here is how I've passed the variables to the template:

echo $template->render(array(
    'categories' => array('1'=>'fruit', '2'=>'cars'),
    'products' => array(array('name' => 'apple', 'category'=>'1')),
));
Sprocket commented 12 years ago

Thanks, I will use the mailing list. I'm using the FuelPHP parser so that may be complicating things. Thanks again.