Access static variable in symfony 2.2 twig
Asked Answered
J

3

12

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?

Jeff answered 14/4, 2013 at 19:59 Comment(0)
S
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

Succinic answered 11/10, 2013 at 15:59 Comment(0)
C
16

just call constant function

{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
Carvajal answered 15/4, 2013 at 14:23 Comment(1)
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.Jeff
I
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') }}
Idealism answered 20/9, 2013 at 0:49 Comment(0)
S
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

Succinic answered 11/10, 2013 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.