Preciel
Preciel

Reputation: 2837

Redirect to route

I want some routes to "exists", but to redirect to another route.

For example, this is what I did with the / route

/**
 * Homepage exists but redirect to projet
 *
 * @Route("/", name="homepage")
 * @Method("GET")
 */
public function indexAction() {
    return $this->redirectToRoute('projet_index');
}

/**
 * @Route("/projets/", name="projet_index")
 * @Method("GET")
 */
public function indexAction() {}

The thing I want to know is if it's this the best method to do it?

Upvotes: 0

Views: 154

Answers (2)

NicolasB
NicolasB

Reputation: 1071

This is somewhat off-topic, but there's a somewhat dirty trick you can use in a similar scenario, where you want to have several URLs resolving to a single route, using placeholders with requirements and default values:

/**
 * @Route("/{path<projets/|>?}", name="projet_index")
 */
public function someAction() {
    // ...
}

The way it works is by defining an optional placeholder (with the {...} syntax) called "path" (though you can call it something else). That placeholder is given requirements with the <...> syntax: it can be either "projets/" or the empty string "". Therefore, both the "/" and the "/projets/" URLs match that route, and nothing else, as they're off the form "/{path}" with a path placeholder that matches its requirements.

So far, so good. But there's still one thing we need to do: give it a default value with the ?, otherwise methods like redirectToRoute or the Twig function path will complain that we aren't given them a value for all the placeholders. Note that you could also use "/{path<projets/|>?projets/}" to make the default value URL "/projets/" instead of "/".

I know it's not exactly what OP wanted, but I think it can be a useful trick to know, and someone having a question similar to OP's might find it useful.

Upvotes: 0

iiirxs
iiirxs

Reputation: 4582

Nope the best way to do that is simple as that:

/**
 * @Route("/", name="homepage")
 * @Route("/projets/", name="projet_index")
 * @Method("GET")
 */
public function indexAction() {
    // your code here
}

Upvotes: 3

Related Questions