Skip to content

Instantly share code, notes, and snippets.

@lucasmezencio
Forked from ajaxray/ToArrayExtension.php
Last active September 3, 2015 20:03
Show Gist options
  • Save lucasmezencio/6de49d115460c3ab3a1c to your computer and use it in GitHub Desktop.
Save lucasmezencio/6de49d115460c3ab3a1c to your computer and use it in GitHub Desktop.
A simple twig extension that adds a to_array filter. It will convert an object to array so that you can iterate over it's properties
# src/YourApp/Bundle/YourBundle/Resources/config/services.yml
services:
core.twig.to_array_extension:
class: Appcito\Bundle\CoreBundle\Twig\ToArrayExtension
tags:
- { name: twig.extension }
<?php
// src/YourApp/Bundle/YourBundle/Twig/ToArrayExtension.php
namespace Appcito\Bundle\CoreBundle\Twig;
/**
* A simple twig extension that adds a to_array filter
* It will convert an object to array so that you can iterate over it's properties
*/
class ToArrayExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('to_array', array($this, 'to_array')),
);
}
public function to_array($object)
{
return get_object_vars($object);
}
public function getName()
{
return 'to_array_extension';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment