如何在网址中显示网页名称,而不是网页ID
例如,它应该是
本地主机/ mysite的/ index.php的/页/约
而不是
本地主机/ mysite的/ index.php的/页面/ 1
我厌倦了编辑actionview()
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
答案 0 :(得分:0)
您可以创建指向您喜欢的任何网址的链接。问题是如何处理传递的数据。
因此,在您看来,创建一个链接。
<a href="<?php echo Yii::app()->createUrl('/mycontroller/view/', array('page'=>'about')); ?>">About Us</a>
这将调用控制器动作actionView()。然后,您可以在那里处理该页面。
public function actionView($page)
{
// Load the model with the required page tag.
$pageDetails = Article::model()->findByAttributes(
array('page_name' => $page)
);
// Display the page
$this->render('view',array(
'model'=>$pageDetails
));
}
答案 1 :(得分:-4)
更新了答案
希望您通过漂亮的网址使您的网站SEO友好。如果您的网页是静态网页,例如about,faq,privacy ...,则可以实现crafter
提供的上述答案。在这种情况下,页面名称应该唯一。
另一种方式(但不完全是你想要的)是用本机yii特征urlManager
重写的URL。在这种情况下,page id
将显示在URL中,如下所示。
本地主机/ mysite的/ index.php的/页面/ 1 /约
本地主机/ mysite的/ index.php的/页/ 2 /英国到支撑意大利的情报省力-ON-移民
如果您观察到,大多数新闻网站都遵循相同的网址结构。
要在应用程序中执行此操作,您必须编写urlManager规则。
'urlManager' => array(
'urlFormat'=>'path',
'showScriptName'=>true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
//We are adding pretty url for article
'page/<id:\d+>/<title:[a-zA-Z0-9\-_]>' => 'page/view',
),
我假设你是Article
数据库表
id title description keywords status
-------------------------------------------------------
1 about some big text some keys active
现在我正在动态制作URl
<?php
//In Controller
//Fetch articles and send them to view
$articles=Articles::model()->findAll();
?>
<?php
//In View
//Iterate articles
foreach($articles as $article)
{
$id=$article->id;
$title=$article->title;
//Make structured Url.
// Replaces all spaces with hyphens and change text to lowercase .
$titleInUrl= strtolower(str_replace(' ', '-', $title));
// Removes special chars.
$titleInUrl=preg_replace('/[^A-Za-z0-9\-]/', '', $titleInUrl);
?>
<a href="<?=yii::app()->baseUrl;?>/page/<?=$id;?>/<?=$titleInUrl;?>">$title</a>
<?php
}
?>
您还可以根据需要更改网址格式。我需要网址
本地主机/ mysite的/ index.php的/页/约-1
为此我在urlManager中有写/更改规则
'page/<title:[a-zA-Z0-9\-_]>-<id:\d+>' => 'page/view',
希望它可以帮助您解决问题。