symfony,twig - 模板中所有变量的默认过滤器

时间:2014-07-20 14:07:00

标签: php symfony twig

假设我想要显示更大的数据集,并且可能存在许多空值/空值。我不想为每个变量定义default filter。 有没有办法在模板中显示所有(空,null)变量的默认值(例如:"未指定")。

修改

树枝:

{# src/KuMiV/EmployeeBundle/Resources/views/Other/detailItem.html.twig #}
{% extends "base.html.twig" %}
...
{% block content %}   
    <h3 class="sub-header">Personenbezogene Angaben</h3>
        <div class="row">
            <div class="col-md-3">             
                <label> ID </label><p>{{ employee.id }} </p>
            </div>
            <div class="col-md-3">  
                <label> Titel </label><p>{{ employee.title|default('keine Angabe') }} </p>
            </div>
            <div class="col-md-3">             
                <label> Vorname </label><p>{{ employee.firstName }} </p>
            </div>
            <div class="col-md-3">                
                <label> Nachname </label><p>{{ employee.lastName }} </p>
            </div>
        </div>
        <div class="row">
            <div class="col-md-3"> 
                <label> Geschlecht </label><p>{{ employee.gender }} </p>
            </div>
            <div class="col-md-3">               
                <label> Email </label><p>{{ employee.email|default('keine Angabe') }} </p>
            </div>
            <div class="col-md-3">               
                <label> Telefon 1</label><p>{{ employee.phone1|default('keine Angabe') }} </p>
            </div>
            <div class="col-md-3">              
                <label> Telefon 2 </label><p>{{ employee.phone2|default('keine Angabe') }} </p>
            </div>
        </div>
        ...
{% endblock content %}

控制器:

class DefaultController extends Controller
{
 public function detailAction($id)
    {
        $employee = $this->getDoctrine("Employee")
                ->getRepository("EmployeeBundle:Employee")
                ->find($id);

        return $this->render('EmployeeBundle:Other:detail.html.twig', array(
            'employee' => $employee,
        ));
    }
}

1 个答案:

答案 0 :(得分:1)

您可能需要为此创建自定义树枝扩展名。

namespace Employee\EmployeeBundle\Twig;
class EmployeeExtension extends \Twig_Extension
{
   public function getFilters()
   {
      return array(
         new \Twig_SimpleFilter('setDefaults', array($this, 'setDefaultFilter')),
      );
   }

   public function setDefaultFilter($employee)
   {
      $employee.title = !empty($employee.title) ? $employee.title : 'keine Angabe';
      $employee.email = !empty($employee.email) ? $employee.email : 'keine Angabe';
      //... So on; continue for others
      return $employee;
   }

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

请记住将扩展名注册为服务:

services:
   employee.twig.employee_extension:
      class: Employee\EmployeeBundle\Twig\EmployeeExtension
      tags:
         - { name: twig.extension }

现在您可以在twig文件中使用它:

{% set employee = employee|setDefaults %}

我仍然相信树枝中的default过滤器更好。