Tobias Schultze
Contributed by Tobias Schultze in #3958

The Routing system is probably one of the most important Component in Symfony. It's a complex beast as it must be flexible, feature-full, and performant at the same time.

Today, let's see a very nice feature that was added to the generator system. I suppose that you all know that Symfony is able to generate two kinds of URLs:

  • absolute URLs: http://example.org/blog/what-a-wonderful-world

    1
    {{ url('blog', { post: 'what-a-wonderful-world' }) }}
  • domain-relative URLs (the default): /blog/what-a-wonderful-world

    1
    {{ path('blog', { post: 'what-a-wonderful-world' }) }}

As of Symfony 2.2 (as of beta2), there are two new kinds of URLs you can generate:

  • schema-relative URLs: //example.org/blog/what-a-wonderful-world

    1
    {{ url('blog', { post: 'what-a-wonderful-world' }, true) }}
  • path-relative URLs: ../ (relative path based on the current URL)

    1
    {{ path('blog', { post: 'what-a-wonderful-world' }, true) }}

Schema-relative URLs are useful for instance when you need to include a resource hosted from an external website (think jQuery from a CDN) on a website where some pages are accessible via HTTP or HTTPS. Instead of using a piece of JavaScript to switch the protocol depending on the protocol used on the page, and to avoid annoying browser warnings, just use a schema-relative URL:

1
//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js

Path-relative URLs comes in very handy if you need to generate static HTML files that can be downloaded to be browsed locally in a browser (think static blog generator for instance). Let's say that you are on the http://example.org/blog/what-a-wonderful-world page and you want to create a link to the main blog page, which URL is http://example.org/blog/, the relative path URL would be: ./:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Generator\UrlGenerator;

// routes
$routes = new RouteCollection();
$routes->add('page', new Route('/blog/{slug}'));
$routes->add('blog', new Route('/blog/'));

// current context
$request = Request::create('http://example.org/blog/what-a-wonderful-world/comments');
$context = new RequestContext();
$context->fromRequest($request);

// create a generator
$generator = new UrlGenerator($routes, $context);

// generate a relative-path URL (will output ./)
echo $generator->generate('blog', array(), UrlGeneratorInterface::RELATIVE_PATH);

Speaking of a static blog generator, we would probably need a global setting to switch from domain-relative URLs (the default) to path-relative URLs (see ticket #6631) when using the path Twig function in templates.

Published in #Living on the edge