Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Last active May 2, 2024 05:51
Show Gist options
  • Save ajaxray/7608395 to your computer and use it in GitHub Desktop.
Save ajaxray/7608395 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