ds342222 2014-10-19 10:52
浏览 29
已采纳

如何在yii2中执行类似'categoryname / seoname'的操作?

I'm doing a project with Yii2. And I'm trying to do so with UrlManager. Like this;

'<CategoryID:\w+>/<SEO:\w+>'=>'soru/goster',

But Yii2 is showing "404 Not found". How do i?

  • 写回答

1条回答 默认 最新

  • duanhe1976 2014-10-19 11:15
    关注

    You can use variables in url rules in config;

    '<category>/<seo>'=>'soru/goster'
    

    Then in your controller (I changed the name as I you didn't post your controller.;

    public function actionGoster($seo) //you can also access $category
    {
      if (isset($seo))
      { 
      //do your lookup 
      }
    }
    

    Access the url like this;

    http://yourDomain/index.php/CATEGORY/SEO/
    

    I do this to look up items in the database which allows for SEO friendly urls;

    'plants/<name>'=>'catalog/viewSingle'
    

    Controller;

    public function actionViewSingle($name)
    {
       if (isset($name)) 
       {
          $model = Plant::model()->findByAttributes(array('url_name'=>$name));
    
          if ($model)
          { //do stuff }
          else
          {
          //do matches and find similar plants that has these characters...
          $this->render('error_matches', array('matches'=>$matches));
          }
       }
       else
       { 
          //404
       }
    

    Edit:

    To avoid all URLs going to this make sure you include default rules;

    '<controller:\w+>'=>'<controller>/',
    '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?