codemix/yii2-localeurls

Different url rules for different languages

insperedia opened this issue · 6 comments

To implement SEO urls in my project I need different urls for different languages, for example:
/en/convert-pdf-to-text
/ru/konvertirovatj-pdf-v-text
/se/konvertera-pdf-i-text

It is really simple to implement. But probably it would be helpful to someone to have this functionality build-in .
I do like this:
Web config:

'ruleConfig' => ['class' =>  'app\classes\UrlRule'],
[                
           'pattern' => 'convert-pdf-to-text',
            'route' => 'convert/pdf-to-text',
            'language' => 'en'
],
[              
           'pattern' => 'kovertirovatj-pdf-v-text',
           'route' => 'convert/pdf-to-text',
           'language' => 'ru'
],

UrlRule class

class UrlRule extends \yii\web\UrlRule
{
    public $language;
    public function createUrl($manager, $route, $params)
    {
        if ($this->language && \Yii::$app->language != $this->language)
            return false;
        return parent::createUrl($manager, $route, $params); // TODO: Change the autogenerated stub
    }
}

Not sure if I understand. But if you already use a custom UrlRule you should not have to specify additional url rules in your config. And inside the UrlRule you can create/parse URLs, as if there was no language code in the URL. The extension should still take care of this.

@insperedia See the MR above. I've added an example UrlRule class. Note that inside createUrl() and parseUrl() you already have the current language in Yii::$app->language. So you can use that to either create or parse the current request.

I've updated the example UrlRule class a little. In createUrl() it creates different slugs depending on the slugLanguage parameter. And in parseUrl() it shows, how you could even redirect to the correct slug translation if so desired.

Mind blowing activity!
Thanks for help, but unfortunately I do not catch an idea.
I just need to have few versions of url that points to same Action and concrete url rules are chosen based on chosen language.
Do not understand why to put configuration data in UrlRule class. What if I have 10 actions and 5 languages then I got crazy switch.
Anyway It was just a suggestion, and my intention was not to make you put a lot of time in it.

Still the case you describe should IMO better be handled by a custom UrlRule class. But if it works for you -fine.

I think this extension is exactly what you need and works perfectly with codemix localeurls.

https://www.yiiframework.com/extension/yii2-translatable-url-rule