2013-11-27 39 views
4

请问是否有语法将“for”标记中的某些元素分开?Twig:“for”标记中的分隔符

比如我有一个用户列表,我想有一个展示自己的用户名“ - ”分隔符,所以预期的结果将是:Mickael - Dave - Chris - ...

我发现这个解决方案:

{% for user in entity.users %} 
    {{ user.name }}{% if not loop.last %} - {% endif %} 
{% endfor %} 

但这不是很优雅。 join过滤器在循环中似乎不太合适。

回答

8

AFAIK,不,您无法使用join过滤器作为您的使用情况,而没有解决方法。这是因为您需要将getName拉出对象属性。 join只是将Traversable实例的每个元素与给定的glue链接起来。

但是,如果您需要它,有一些解决方法。

添加一个__toString方法

在你User的实体,您可以添加一个__toString方法来获取默认的用户名。
如果没有其他对象使用当前的默认toString你应该然而照顾,因为它可能会导致冲突

namespace Acme\FooBundle\Entity; 

class User 
{ 
    public function __toString() 
    { 
     return $this->getName(); 
    } 
} 

然后你就可以在你的树枝使用join过滤

{{ entity.users|join(' - ') }} 

地图中的用户名控制器

在您的控制器中,在将参数发送到视图之前,可以映射它们的所有用户名以适合数组。
注:我假设是PersistentCollection,如果没有,在你的树枝使用array_map代替

// Acme/FooBundle/Controller/MyController#fooAction 

$users = $entity->getUsers(); 
$usernames = $users->map(function(User $user) { 
    return $user->getName(); 
}); 

return $this->render('AcmeFooBundle:My:foo.html.twig', array(
    'entity' => $entity, 
    'usernames' => $usernames 
); 

然后

{{ usernames|join(' - ') }} 

创建树枝过滤

在你的应用程序中,可以创建一个Twig Extension。在这个例子中,我将创建一个名为joinBy的过滤器,它将通过指定一个用于连接元素的方法来表现为join

服务声明

直和轻松,没有太苛刻,但一个标准的声明像文档

服务。阳明海运

acme_foo.tools_extension: 
    class: Acme\FooBundle\Twig\ToolsExtension 
    tags: 
     - { name: twig.extension } 

扩展的创建

@Acme \ FooBundle \嫩枝\ ToolsExtension

namespace Acme\FooBundle\Twig; 

use Twig_Extension, Twig_Filter_Method; 
use InvalidArgumentException, UnexpectedValueException; 
use Traversable; 

/** 
* Tools extension provides commons function 
*/ 
class ToolsExtension extends Twig_Extension 
{ 
    /** 
    * {@inheritDoc} 
    */ 
    public function getName() 
    { 
     return 'acme_foo_tools_extension'; 
    } 

    /** 
    * {@inheritDoc} 
    */ 
    public function getFilters() 
    { 
     return array(
      'joinBy' => new Twig_Filter_Method($this, 'joinBy') 
     ); 
    } 

    /** 
    * Implode-like by specifying a value of a traversable object 
    * 
    * @param mixed $data Traversable data 
    * @param string $value Value or method to call 
    * @param string $join Join string 
    * 
    * @return string Joined data 
    */ 
    public function joinBy($data, $value, $join = null) 
    { 
     if (!is_array($data) && !($data instanceof Traversable)) { 
      throw new InvalidArgumentException(sprintf(
       "Expected array or instance of Traversable for ToolsExtension::joinBy, got %s", 
       gettype($data) 
      )); 
     } 

     $formatted = array(); 

     foreach ($data as $row) { 
      $formatted[] = $this->getInput($row, $value); 
     } 

     return implode($formatted, $join); 
    } 

    /** 
    * Fetches the input of a given property 
    * 
    * @param mixed $row An array or an object 
    * @param string $find Property to find 
    * @return mixed Property's value 
    * 
    * @throws UnexpectedValueException When no matching with $find where found 
    */ 
    protected function getInput($row, $find) 
    { 
     if (is_array($row) && array_key_exists($find, $row)) { 
      return $row[$find]; 
     } 

     if (is_object($row)) { 
      if (isset($row->$find)) { 
       return $row->$find; 
      } 

      if (method_exists($row, $find)) { 
       return $row->$find(); 
      } 

      foreach (array('get%s', 'is%s') as $indic) { 
       $method = sprintf($indic, $find); 

       if (method_exists($row, $method)) { 
        return $row->$method(); 
       } 
      } 

      if (method_exists($row, $method)) { 
       return $row->$method(); 
      } 
     } 

     throw new UnexpectedValueException(sprintf(
      "Could not find any method to resolve \"%s\" for %s", 
      $find, 
      is_array($row) 
       ? 'Array' 
       : sprintf('Object(%s)', get_class($row)) 
     )); 
    } 
} 

使用

现在,您可以通过调用用它在你的树枝

{{ entity.users|joinBy('name', ' - ') }} 
# or 
{{ entity.users|joinBy('getName', ' - ') }} 
+0

太好了,谢谢! – ncrocfer

1

在实体类中添加__toString()方法,并且完成。

并使用本机Twig的join过滤器,如在{{ entity.users|join(' - ') }}中那样。

+0

太棒了!谢谢 – Ld91