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?

3 Answers 3

16

just call constant function

{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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') }}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.