2

After learning how to use dynamic routing in MyPluginPlugin.php, I quickly ran into the issue of if the URL has special characters from url_encode:

public function registerSiteRoutes()
{
return array(
    'myroute/(?P<myVariable>[-\w]+)' => array('action' => 'myPlugin/myAction')
);    
}

And then I process some variables before rendering the template in myPlugin/myAction:

 public function actionLoadTemplate( array $variables = array() )
 {
   /*
   process & build $variables
   */

    $this->renderTemplate('layouts/forums/_entry', $variables);

 }

This works great if the route looks like myroute/check-this-out, however if the route had a special character in it, say it was "check-this-out!", it understandably leads to a 404. But with using url_encode on the URL so it looks like myroute/check-this-out%21, it still leads to a 404.

When testing manually in the CP route section, if I create myroute/* with the token, I don't get a 404 with those special characters after using url_encode.

Is there a way to modify (?P<myVariable>[-\w]+) so that it works with url-safe special characters just like the CP version does?

4

You'll need to update the regex to allow for additional characters. For example, if you want to allow !, then this will work:

return array(
    'myroute/(?P<myVariable>[-\w\!]+)' => array('action' => 'myPlugin/myAction')
); 

Note that \w is essentially the same as writing [A-Za-z0-9_].

| improve this answer | |
  • But this does work when manually adding the route in CP using the aterisk, as long as the url/route uses url_encode. Characters like "!" aren't being passed in the route, the url_encode() character is (such as %21) There must be a way to do '(?P<myVariable>[-\w]+)' in order to get the same functionality as the CP asterisk token no? – taylor Mar 19 '15 at 23:03
  • You're right, I'm an idiot. Updating answer. – Brad Bell Mar 19 '15 at 23:18
  • Nifty trick, super good to know. Works perfectly! – taylor Mar 19 '15 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.