Code snippets for symfony 1.x

Navigation

Default trailing slash for simple routes

Here is my solution for trailing slash in simple localized urls.

In routing.yml add:

homepage_lang:
  url:   /:sf_culture:sf_slash
  param: { module: main, action: index }
  requirements:
    sf_culture: (?:pl|en|de)
    sf_slash: '\/?'
  options:
    suffix: ''
    segment_separators: []
 

Both urls will work now: '/en' & '/en/'

But if you try to use link_to helper

<?php
echo link_to('Homepage', '@homepage_lang');
 

It will require sf_slash parameter.

Notice: sf_culture will be set automagically from current user culture unless you add to route: '@homepage_lang?sf_culture=de'.

There are (at least) 2 solutions for this. First is to add default sf_slash parameter in routing:

homepage_lang:
  url:   /:sf_culture:sf_slash
  param: { module: main, action: index, sf_slash: '' }
  requirements:
    sf_culture: (?:pl|en|de)
    sf_slash: '\/?'
  options:
    suffix: ''
    segment_separators: []
 

And everything will work just fine, link_to() helper will generate urls like: '/en', '/de' etc.

But what if we want trailing slash to be added every time we generate a link? It's more difficult and it's our 2nd solution for required parameter.

Routing rule should look like in the first example:

homepage_lang:
  url:   /:sf_culture:sf_slash
  param: { module: main, action: index }
  requirements:
    sf_culture: (?:pl|en|de)
    sf_slash: '\/?'
  options:
    suffix: ''
    segment_separators: []
 

But we need set sf_flash somehow. To do so, I used filters (was suggested in symfony book 1.2, chapter 9).

Create slashFilter in applications lib directory (app/lib/slashFilter.class.php):

<?php
 
class slashFilter extends sfFilter
{
   public function execute($filterChain)
   {
      $this->getContext()->getRouting()->setDefaultParameter('sf_slash', '/');
      $filterChain->execute();
   }
}
 

And add it to filters.yml:

# You can find more information about this file on the symfony website:
# http://www.symfony-project.org/reference/1_4/en/12-Filters
 
rendering: ~
security:  ~
 
# insert your own filters here
slashFilter:
  class: slashFilter
 
cache:     ~
execution: ~
 

Eventually clear your cache and trailing slash will be added to @homepage_lang route.

But there can be another problem and your slash / will be added as '%2F'. You can play with .htaccess or server configuration but I just created my own link_to() or url_for() helpers which replaces '%2F' with '/' like:

<?php
$url = str_replace('%2F', '/', $url);
 

Any improvements are appreciated ;)

by rozwell on 2010-10-03, tagged routing  slash  trailing