Zend_View_Helper_HeadStyle amélioré
Par SandRock le jeudi 25 septembre 2008, 17:21 - Dev - Lien permanent
Le Zend_View_Helper_HeadStyle de Zend Framework a un bug non corrigé depuis très longtemps, à savoir ZF-3406. Le bug en question empèche la création d'une balise <style> avec un attribut media contenant une liste de différents médias.
$this->headStyle()->captureStart(Zend_View_Helper_Placeholder_Container_Abstract::APPEND, array('media' => 'screen')) // Displays <style type="text/css" media="screen"> $this->headStyle()->captureStart(Zend_View_Helper_Placeholder_Container_Abstract::APPEND, array('media' => array('screen', 'projection', 'tv'))) // Should display <style type="text/css" media="screen projection tv"> // But displays <style type="text/css">
Donc, voici un nouvel helper modifié qui fait son job :
<?php require_once 'Zend/View/Helper/HeadStyle.php'; /** * HeadStyle helper * * @uses helper Zend_View_Helper */ class App_View_Helper_HeadStyle extends Zend_View_Helper_HeadStyle { /** * Convert content and attributes into valid style tag * * @param stdClass $item Item to render * @param string $indent Indentation to use * @return string */ public function itemToString(stdClass $item, $indent) { $attrString = ''; if (!empty($item->attributes)) { foreach($item->attributes as $key => $value) { if (!in_array($key, $this->_optionalAttributes)) { continue; } if ('media' == $key) { if (is_string($value) && preg_match('/^[\w ]+$/', $value)) { $value = explode(' ', $value); } if (is_array($value)) { $stringValue = ''; $separator = ''; foreach ($value as $mediaType) { if (!in_array($mediaType, $this->_mediaTypes)) { continue; } $stringValue .= $separator.$mediaType; $separator = ' '; } $value = $stringValue; } else { if (!in_array($value, $this->_mediaTypes)) { continue; } } } $attrString .= sprintf(' %s="%s"', $key, htmlspecialchars($value)); } } $html = '<style type="text/css"' . $attrString . '>' . PHP_EOL . $indent . '<!--' . PHP_EOL . $indent . $item->content . PHP_EOL . $indent . '-->' . PHP_EOL . '</style>'; return $html; } }
On spécifier au Broker de le charger de préférence à celui de zf :
$this->view->setHelperPath(Zend_Registry::get('conf')->paths->views.'helpers/', 'App_View_Helper');
Et ça s'utilise de cette façon :
$this->headStyle()->captureStart(Zend_View_Helper_Placeholder_Container_Abstract::APPEND, array('media' => array('screen', 'print', 'projection', 'tv'))); $this->headStyle()->captureStart(Zend_View_Helper_Placeholder_Container_Abstract::APPEND, array('media' => 'screen print projection tv'));