All websites contain static pages, whose content is static.
To create a static page in a common way, we need to:
action
) to execute action in Controller
Append the following action to Controller
:
public function actionInfo() { return $this->render('info'); }
Then, create a view in views/controller/action-name.php
. This procedure is simple but too long and redundant.
Yii2 provides a quick alternative, adding static pages to the actions()
method of Controller
as follows:
public function actions() { return [ 'pages' => [ 'class' => 'yiiwebViewAction', ], ]; }
With this simple declaration, we can put all static content under views/controllerName/pages
.
Finally, we can point to the URL with route controller_name/page
and the view
parameter with the name of a view file such as http://hostname/basic/web/index.php?r=controllerName/pages&view=name_of_view
.
After we have learned how to create a static page, it is time to write a contact page.
Let's put a short static content in views/site/pages/contact.php
as follows:
To contact us, please write to [email protected]
Then, let's add a page
attribute in the return array from the actions()
method of Controller
. To simplify, we will use SiteController
that has this default implementation of the actions()
method:
public function actions() { return [ 'error' => [ 'class' => 'yiiwebErrorAction', ], 'captcha' => [ 'class' => 'yiicaptchaCaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; }
After the last attribute, we will append the page
attribute, and the following will be the result:
public function actions() { return [ 'error' => [ 'class' => 'yiiwebErrorAction', ], 'captcha' => [ 'class' => 'yiicaptchaCaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], 'pages' => [ 'class' => 'yiiwebViewAction', ], ]; }
Now, every request to site/pages/
is routed using the ViewAction
class, which handles it simply by rendering static content of relative view.
Test it by clicking on http://hostname/basic/web/index.php?r=site/pages&view=contact
, and we should see this:
We can customize the last part of the route with these changes:
actions()
method of Controller
viewPrefix
attribute of the ViewAction
class declaration with the first part of the URL that we want to use to reach the pagesviews/controllerName
For example, we want to use static
as the last part of the URL to reach static pages in SiteController
.
We want to point to http://hostname/basic/web/index.php?r=site/static&view=contact
to display the contact view.
This will be the ViewAction
node in the array from the actions()
method of SiteController
:
'static' => [ 'class' => 'yiiwebViewAction', 'viewPrefix' => 'static' ],
We must also change the name of the static pages subfolder, renaming it from views/site/pages
to views/site/static
, and we can point to http://hostname/basic/web/index.php?r=site/static&view=contact
.
3.147.42.168