2013-04-14 17 views
9

Ich habe eine Klasse enthält, konstant Optionen in Array-Form:Zugang statische Variablen in symfony 2.2 Zweig

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

Wie kann ich auf $ UNVERSITY_STANDING oder GENDER $ in symfony 2.2 Zweig?

Antwort

2

Meine Lösung für ein Problem wie dies ist ein statisches Element in der TwigExtention zu erstellen:

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

eine Funktion in der Extention erstellen:

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

Und das in dem Zweig nennen:

{{"something"|getStatic}} 

Grüße

10

just call constant function

{{ constant('Namespace\\Classname::CONSTANT_NAME') }} 
+7

Vielen Dank für Ihre Antwort. Wie auch immer, ich habe Ihren Vorschlag für den Zugriff auf konstante Variablen verwendet. Es funktioniert jedoch immer noch nicht für den Zugriff auf statische Variablen. – Floricel

6

Sie können wie unten eine benutzerdefinierte Zweig Funktion erstellen:

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

Dann fügen Sie es in Twig

$twig->addFunction($staticFunc); 

Jetzt können Sie diese Funktion aus Ihrer Sicht aufrufen

{{ static('YourNameSpace\\ClassName', 'VARIABLE_NAME') }}