I’ve been getting to know Zend Framework, and despite it being awesome so far, there’s a few quirks I just don’t understand… maybe I missed something…
Anyway, David Cooper posted a quick howto on adding CSS to a Zend Framework page, which works and is all well and good, but there was a problem. The code that Zend Framework spits out was not XHTML valid. As I said, I might’ve missed something out, and this might be a really convoluted way of doing things, but give me a break, I’m just learning it!
Firstly, in your controller’s action (e.g. IndexController::indexAction), add a list of CSS files:
$css_files = array('index.css','test.css'); $this->getFrontController()->setParam('css',$css_files);
Modify the list of CSS files to suit your needs. Note that the $css_files must be an array, otherwise the helper class will ignore it. Now add a new PHP file in application/views/helpers called ‘CssInclude.php’, and put this in it:
<?php class Zend_View_Helper_CssInclude { function cssInclude() { $output = ''; $fc = Zend_Controller_Front::getInstance(); $baseUrl = $fc->getBaseUrl(); $css_files = $fc->getParam('css'); if(is_array($css_files)) { foreach($css_files as $css_file) { $output .= ' <link rel="stylesheet" type="text/css" media="screen" href="'; $output .= $baseUrl . '/css/' . $css_file . "\" />\n"; } } return $output; } }
This is a helper class that takes the parameter you set in the controller, and simply churns out an XHTML valid <link> tag. There’s just one more step, add this in your layout or view:
<?php echo $this->cssInclude(); ?>
And voila! If there’s a better way of doing this, then I’d like to know!
April 10th, 2009 at 1:14 pm
What happens when you add this to the front controller?
require_once ‘Zend/View/Helper/Doctype.php’;
$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype( XHTML1_TRANSITIONAL );
April 11th, 2009 at 9:47 am
Hello, our way to do this is in a Controller_Action base class adding a protected method that do the job.
The result is that each action in each module can do a $this->addCssFile(‘nameOfTheCss’);
The method add the css with the HeadLink view helper and before this verify that the css file exists.
Then all we have to do is an echo of $this->headLink() in a view
Same is applicable for javascript with HeadScript view helper.
April 14th, 2009 at 8:19 am
Cheers for the linkback
And as the first comment said, I’ve got this in my controller, before the dispatch() line.
$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype(‘XHTML1_STRICT’);
April 14th, 2009 at 11:40 am
Oh ace, that’ll probably sort it, I’ll give that a try, cheers!