11

I have a class containing constant options in array form:

namespace MyNameSpace;

class OptionConstants
{
  /**
   * Gender options
   */
   public static $GENDER = array(
    'Male',
    'Female'
   );

  /**
   * University year levels
   */
   public static $UNVERSITY_STANDING = array(
    '--None--',
    'First Year',
    'Second Year',
    'Third Year',
    'Fourth Year',
    'Graduate Student',
    'Graduated',
    'Other'
   );
}

How can I access $UNVERSITY_STANDING or $GENDER in symfony 2.2 twig?

Floricel
  • 791
  • 2
  • 9
  • 20

3 Answers3

15

just call constant function

{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
Marino Di Clemente
  • 3,120
  • 1
  • 23
  • 24
  • 12
    Thank you for your answer. Anyway, I have used your suggested way in accessing constant variables. However, it still does not work for accessing static variables. – Floricel Apr 18 '13 at 15:13
9

You can create a custom Twig function as below:

$staticFunc = new \Twig_SimpleFunction('static', function ($class, $property) {
        if (property_exists($class, $property)) {
            return $class::$$property;
        }
        return null;
    });

Then add it into Twig

$twig->addFunction($staticFunc);

Now you can call this function from your view

{{ static('YourNameSpace\\ClassName', 'VARIABLE_NAME') }}
Alex Hoang
  • 171
  • 2
  • 3
3

My Solution for a problem like this is to create a static member in the TwigExtention:

class TwigExtension extends \Twig_Extension
{
    private static $myStatic = 1;
    ...

Create a Funktion in the Extention:

public function getStatic($something)
{
    self::$myStatic += 1;
    return self::$myStatic;
}

And call this in the twig:

{{"something"|getStatic}}

Greetings

Mic
  • 523
  • 6
  • 18