我应该在哪里找到与Zend Framework中的布局相关的逻辑?

时间:2011-06-16 18:22:28

标签: zend-framework zend-view zend-layout

我需要自定义body标签的属性。我应该在哪里找到逻辑?在基本控制器中,查看助手?

这应该是布局

<?=$this->doctype() ?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        ...
    </head>
    <body<?=$this->bodyAttrs?>>  <!-- or <?=$this->bodyAttrs()?> -->
        ...
    </body>
</html>

这应该是控制器中的变量声明

class Applicant_HomeController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->idBody = "someId1";
        $this->classesBody = array("wide","dark");
    }

    public function loginAction()
    {
        $this->idBody = "someId2";
        $this->classesBody = array();
    }

    public function signUpAction()
    {
        $this->idBody = "someId3";
        $this->classesBody = array("no-menu","narrow");
    }
}

这是连接属性的函数。

/**
  * @param string $idBody     id Attribute
  * @param array $classesBody class Attribute (array of strings)
  */
protected function _makeBodyAttribs($idBody,$classesBody)
{
    $id = isset($idBody)?' id="'.$idBody.'"':'';
    $hasClasses = isset($classesBody)&&count($classesBody);
    $class = $hasClasses?' class="'.implode(' ',$classesBody).'"':'';
    return $id.$class;
}

我需要最后一个胶水代码。

1 个答案:

答案 0 :(得分:2)

为你做得更好:

<?php
class My_View_Helper_Attribs extends Zend_View_Helper_HtmlElement
{

    public function attribs($attribs) {
        if (!is_array($attribs)) {
            return '';
        }
        //flatten the array for multiple values
        $attribs = array_map(function($item) {
           if (is_array($item) {
                return implode(' ', $item)
           }
           return $item;
        }, $attribs);
        //the htmlelemnt has the build in function for the rest
        return $this->_htmlAttribs($attribs)
    }
}

在您的控制器中:

public function indexAction()
{
    //notice it is $this->view and not just $this
    $this->view->bodyAttribs= array('id' => 'someId', 'class' => array("wide","dark"));
}

public function loginAction()
{
    $this->view->bodyAttribs['id'] = "someId2";
    $this->view->bodyAttribs['class'] = array();
}
在您的视图脚本中

<body <?= $this->attribs($this->bodyAtrribs) ?>>