我试图用额外的选项(参数)构建一个简单的视图。当我使用/ product /和/ product / index时,视图会显示,但我想添加参数来选择每个id的帖子。
因为我在已经构建的yii2项目中工作可能设置不正确或需要设置,我不知道但是当我使用参数时它将向我显示页面未找到错误(在布局内)。 / p>
www.example.com/products/ // view works
www.example.com/products/index/ // view works
www.example.com/products/id/extraparam //view not working (how I want it to be)
控制器
public $defaultAction = 'index';
public function actionIndex( $id , $par)
{
$proid = $id; // we want to use this if present
$extra = $par; // we want to use this if present
// as we do not need the layout
$this->layout = false;
return $this->render('index');
}
答案 0 :(得分:1)
您需要在主配置中编辑UrlManager设置。
'urlManagerFrontend' => [
'class' => 'yii\web\UrlManager',
'baseUrl' => 'https://somedomain/', // if you want to prepend domain name to all links
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<module:[a-z-]+>/<controller:[a-z-]+>/<action:[a-z-]+>/<id:\d+>/<param:[a-z-]+>' => '<module>/<controller>/<action>',
'<module:[a-z-]+>/<controller:[a-z-]+>/<action:[a-z-]+>' => '<module>/<controller>/<action>',
'<controller:[a-z-]+>/<id:\d+>' => '<controller>/view',
'<controller:[a-z-]+>/<action:[a-z-]+>/<id:\d+>' => '<controller>/<action>',
'<controller:[a-z-]+>/<action:[a-z-]+>/<id:\d+>/<param:[a-z-]+>' => '<controller>/<action>',
'<controller:[a-z-]+>/<action:[a-z-]+>' => '<controller>/<action>',
],
],
你将有另一个参与某些规则的参数
(在这个例子中, param 必须匹配模式[a-z-]
)
要创建网址,您需要指定 param :
Url::to(['product/edit', 'id' => 4, 'param' => 'sample-product']);
// this will link to: /product/edit/4/sample-product
您可以尝试自定义规则,使用多个参数,等等。
请记住,yii将始终使用与匹配的网址匹配的第一条规则
'<controller:[a-z-]+>/<id:\d+>/<param:[a-z-]>' => '<controller>/view'
// this will match your exact case for actionView