Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static variable in symfony 2.2 twig

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?

like image 965
Floricel Avatar asked Apr 14 '13 19:04

Floricel


People also ask

What are the disadvantages of using environment variables in Symfony?

The main issue of env vars is that their values can only be strings and your application may need other data types (integer, boolean, etc.). Symfony solves this problem with "env var processors", which transform the original contents of the given environment variables.

Should I use env VARs in Symfony?

Using env vars to configure Symfony applications is a common practice to make your applications truly dynamic. The main issue of env vars is that their values can only be strings and your application may need other data types (integer, boolean, etc.).

What processors are available in Symfony?

Symfony provides the following env var processors: Casts FOO to a bool ( true values are 'true', 'on', 'yes' and all numbers except 0 and 0.0; everything else is false ):


3 Answers

just call constant function

{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
like image 53
Marino Di Clemente Avatar answered Nov 07 '22 16:11

Marino Di Clemente


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') }}
like image 41
Alex Hoang Avatar answered Nov 07 '22 16:11

Alex Hoang


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

like image 37
Mic Avatar answered Nov 07 '22 16:11

Mic