2011-09-11 3 views
11
나는 다음과 같은 코드를 수행 할

:변수로 결정되는 Twig 멤버에 어떻게 액세스합니까?

{% set rooms = [] %} 
{% set opts = { 
    'hasStudio': 'Studio', 
    'has1Bed': '1 BR', 
    'has2Bed': '2 BR', 
    'has3Bed': '3 BR', 
    'has4BedPlus': '4 BR+' 
} 
%} 
{% for key, val in opts %} 
    {% if bldg.{key} is none %} {# PROBLEM HERE.. HOW TO FIND THIS MEMBER!? #} 
     {{ val }}? 
    {% elseif bldg.{key} %} 
     {{ val }} 
    {% else %} 
     No {{ val }} 
    {% endif %} 
{% endfor %} 

가 어떻게 key의 값으로 명명 된 빌딩의 멤버 속성을 호출 할을? 나는

bldg.hasStudio 
bldg.has1Bed 
bldg.has2Bed 
etc.... 

답변

3

나는이 일을 내 자신의 나뭇 가지 확장을 썼다.당신은 내가 원하는 방법으로 그것을 사용하는 것입니다 : 여기

{% set keyVariable = 'propertyName' %} 
{{ obj.access(keyVariable) }} 
{# the above prints $obj->propertyName #} 

하는 것이 그 것이다 :

// filename: Acme/MainBundle/Extension/AccessTwigExtension.php 
namespace Acme\MainBundle\Extension; 

class AccessTwigExtension extends \Twig_Extension 
{ 
    public function getFilters() 
    { 
     return array(
      'access' => new \Twig_Filter_Method($this, 'accessFilter'), 
     ); 
    } 

    public function getName() 
    { 
     return 'access_twig_extension'; 
    } 

    // Description: 
    // Dynamically retrieve the $key of the $obj, in the same order as 
    // $obj.$key would have done. 
    // Reference: 
    // http://twig.sensiolabs.org/doc/templates.html 
    public function accessFilter($obj, $key) 
    { 
     if (is_array($obj)) { 
      if (array_key_exists($key, $obj)) { 
       return $obj[$key]; 
      } 
     } elseif (is_object($obj)) { 
      $reflect = new \ReflectionClass($obj); 
      if (property_exists($obj, $key) && $reflect->getProperty($key)->isPublic()) { 
       return $obj->$key; 
      } 
      if (method_exists($obj, $key) && $reflect->getMethod($key)->isPublic()) { 
       return $obj->$key(); 
      } 
      $newKey = 'get' . ucfirst($key); 
      if (method_exists($obj, $newKey) && $reflect->getMethod($newKey)->isPublic()) { 
       return $obj->$newKey(); 
      } 
      $newKey = 'is' . ucfirst($key); 
      if (method_exists($obj, $newKey) && $reflect->getMethod($newKey)->isPublic()) { 
       return $obj->$newKey(); 
      } 
     } 
     return null; 
    } 
} 

내 프로그램에서 사용하려면, 나 또한 내 의존성 주입에 몇 줄을 추가했다 :

//filename: Acme/MainBundle/DependencyInjection/AcmeMainInjection.php 
// other stuff is here.... 
public function load(array $configs, ContainerBuilder $container) 
{ 
    // other stuff here... 
    $definition = new Definition('Lad\MainBundle\Extension\AccessTwigExtension'); 
    $definition->addTag('twig.extension'); 
    $container->setDefinition('access_twig_extension', $definition); 
    // other stuff here... 
2

사용 괄호 구문의 값을 얻으려면 :

+2

죄송합니다,이 개체에 대한 배열을 위해 작동하지만,하지 :( –

1

bldg[key]는 일반적으로 당신은

{% test.getAction() %} 

시험 물체와 getAction()는 함수 인 점 연산자를 사용하여 개체에 액세스 할 수 있습니다.

21

짧은 대답 : 아니 직접/기본적으로 가능한 ... 아직.

분명히 그들은 정확히 그 필요성을 해결하는 attribute()이라는 새로운 기능을 Twig 1.2에 추가했습니다.

하지만 현재까지는 Twig 1.1.2 만 다운로드 할 수 있습니다. 그래서 버전 번호를 찾을 수는 없지만 아마 1.2는 SF2와 함께 제공되지 않을 것입니다. (현재 1.2를 사용할 수 있습니다!)

다른 트릭으로 해결하려고했지만 아무 소용이 없었습니다. 1.2 수정됩니다.

버전 1.2의 새로운 기능 : 속성 함수가 Twig 1.2에 추가되었습니다.

속성은 변수의 "동적"속성에 액세스 할 수 있습니다 :

{{ attribute(object, method) }}

{{ attribute(object, method,arguments) }}

{{ attribute(array, item) }}


그러나 당신은하지만 무엇을 할 수 있는지은 필요에 따라 처리하는 클래스에 메소드를 추가합니다. 그런 일 :

PHP :

class C 
{ 
    public $a = 1; 
    public $b = 2; 

    public function getValueForKey($k) 
    { 
     return $this->$k; 
    } 
} 

[ providing an instance of C to the template as 'obj' ] 

나뭇 가지 :

{% set x = "a" %} 
{{ obj.getValueForKey(x) }} 

가 출력 '1'

+0

감사를 정보를 원하시면.이 솔루션을 내 문제는 내가 나뭇 가지 요구하기 때문에 단지가 게터 내 엔티티 클래스를 진흙 싶지 않았다이다 그들 ... 나뭇 가지 1.2에서 –

+1

속성 기능이 멋지다. –

관련 문제