2009年5月6日星期三

[fw-mvc] Re: Head* view helpers and baseUrl

I ended up subclassing the headScript/headLink helpers to automatically use my baseUrl helper when it detects a relative path. The only problem is that my subclassed headLink helper is nearly identical to the subclassed headScript helper, except that it looks for "Stylesheet" in the method passed to __call() instead of "File".

It would be nice if ZF offered this kind of functionality out-of-the-box, because I am sure that there are other developers that are using ZF in a subdirectory.

Here is my subclassed headScript helper:

<?php

/**
 * Modified to allow prepending of the baseUrl for relative paths
 *
 */
class My_View_Helper_HeadScript extends Zend_View_Helper_HeadScript
{
/**
* Prepends the base URL for relative paths
*
* @param string $method
* @param array $args
*/
public function __call($method, $args)
{
if (preg_match('/File$/', $method) AND isset($args[0])) {
// Prepend base url for relative paths
if (!preg_match('+^(/|(ht|f)tps?://)+', $args[0])) {
$args[0] = $this->view->baseUrl($args[0]);
}
}
return parent::__call($method, $args);
}
}

The baseUrl helper just prepends the string with the value returned from Zend_Controller_Front::getInstance()->getBaseUrl().


-Hector


On Wed, May 6, 2009 at 2:10 PM, Hector Virgen <djvirgen@gmail.com> wrote:
Would it be possible to make the Head* view helpers baseUrl-aware like the url() view helper for relative paths? I currently have my ZF application installed in a subdirectory which is breaking relative urls for css and js files.

For example:

<?= $this->headLink()->appendStylesheet('css/styles.css') ?>

Results in:

<link href="css/default.css" media="screen" rel="stylesheet" type="text/css" />
When I'm on the homepage of my site at http://www.example.com/~hvirgen/myzfapp, the CSS file can be read because the relative path maps to its physical location.

But when I start navigating into the site it throws off my relative paths:

css relative path: css/style.css

If my ZF application was in the webroot, then it would be perfectly fine to prepend all the paths with a forward-slash (/css/style.css), but my project is going to be deployed in a subdirectory that is different than my development directory (as in, it won't be /~hvirgen/myzfapp when we go live).

One suggestion I was given a while back was to create a baseUrl view helper, but it is becoming tedious and repetitive to wrap all of my relative urls in that helper.

-Hector

没有评论: