Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting basepath from view in zend framework

Case: you're developing a site with Zend Framework and need relative links to the folder the webapp is deployed in. I.e. mysite.com/folder online and localhost:8080 under development.

The following works nice in controllers regardless of deployed location:

$this->_helper->redirector->gotoSimple($action, $controller, $module, $params);

And the following inside a viewscript, ie. index.phtml:

<a href="<?php echo $this->url(array('controller'=>'index', 'action' => 'index'), null, true); ?>">

But how do I get the correct basepath when linking to images or stylesheets? (in a layout.phtml file, for example):

<img src='<?php echo WHAT_TO_TYPE_HERE; ?>images/logo.png' />

and

$this->headLink()->appendStylesheet( WHAT_TO_TYPE_HERE . 'css/default.css');

WHAT_TO_TYPE_HERE should be replaced with something that gives

<img src="/folder/images/logo.png />` on mysite.com and `<img src="/images/logo.png />

on localhost

like image 203
Mads Mobæk Avatar asked Mar 11 '09 18:03

Mads Mobæk


1 Answers

You can get the base url from the Front Controller Zend_Controller_Front::getInstance()->getBaseUrl();. I wrap that in a view helper

class My_View_Helper_BaseUrl 
{   
    /**
     *  Get base url
     * 
     * @return string
     */
    public function baseUrl()
    {
        return rtrim(Zend_Controller_Front::getInstance()->getBaseUrl(),'/');
    }

}

So in the html markup you have something like <img src="<?php echo $this->baseUrl();?>/images/logo.png"/> The trailing slash is stripped out in the helper so that when the application isn't run in a sub folder (baseUrl is blank in that case) the path will still work.

like image 106
Akeem Avatar answered Oct 06 '22 17:10

Akeem