开发者

How to add a trailing slash on URL

开发者 https://www.devze.com 2023-04-05 16:05 出处:网络
I would like all URLs on my site to have a trailing slash on the URL. I created a simple extension for the URLHelper in Zend. Right now it changes all the word separators to hyphens (-). Adding the fu

I would like all URLs on my site to have a trailing slash on the URL. I created a simple extension for the URLHelper in Zend. Right now it changes all the word separators to hyphens (-). Adding the functionality to append a trailing slash would be great. The commented out line (hack) didn't work. The slash ended up being url-encoded.

I know this has to be an easy fix and right in front of my face, but it's escaping me. :\

    class Ace_Helpers_Url extends Zend_View_Helper_Url
{

   /**
    * Generates an url given the name of a route.
    *
    * @access public
    *
    * @pa开发者_开发百科ram  array $urlOptions Options passed to the assemble method of the Route object.
    * @param  mixed $name The name of a Route to use. If null it will use the current Route
    * @param  bool $reset Whether or not to reset the route defaults with those provided
    * @return string Url for the link href attribute.
    */
   public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = false)
   {
      if (is_array($urlOptions)) {
         foreach ($urlOptions as $index => $option) {
            $urlOptions[$index] = trim(strtolower(str_replace(' ', '-', $option)));
            #$urlOptions[$index] .= '/'; #Add trailing slash for continuity
         }
      }
      $router = Zend_Controller_Front::getInstance()->getRouter();
      return $router->assemble($urlOptions, $name, $reset, $encode);
   }
}


Appending it manually isn't really that hard:

<?php echo $this->url(array(
        'controller' => 'index'
    )).'/'; ?>

If you want to avoid url encoding, check out the fourth parametre to the url helper: encode. Set it to false and it will not url-encode your input, so you can do something like this:

<?php echo $this->url(array(
        'alias' => 'blog/2011/09/example-blog-entry'
    ),'alias',true,false); ?>


My solution is based on this discussion.

application/view/helpers/Url2.php

class Zend_View_Helper_Url2 extends Zend_View_Helper_Url
{
    /**
     * Keeps Url()'s original params and their default values, so we don't have to
     * learn yet another method.
     */
    public function url2(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        return parent::url($urlOptions, $name, $reset, $encode) . '/';
    }
}

in some controller

echo $this->view->url2(array('controller' => 'index'));

or some view

echo $this->url2(array('controller' => 'index'));
0

精彩评论

暂无评论...
验证码 换一张
取 消