Reputation: 2207
Just installed the yii2 framework and playing with it, but i cant seem to get it to work with files that are located inside a folder.
All other pages(index,contact,about,index etc) are inside the views/site
folder, but I added a new folder to the views
folder called blog
which contains a new view called index.php
.
folder structure:
project
- views
-- site
--- index.php
--- about.php
--- (more files)
-- blog
--- index.php
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionBlog()
{
// not working
return $this->render('blog/index');
}
}
Upvotes: 1
Views: 2045
Reputation: 23788
Use the path simply no use to create the controller with name Blog
specifically, just add
return $this->render('/blog/index')
inside your new action actionBlog()
in the SiteController
.
Just remember that if you are not following Yii
convention of using the controllers
and view
, start the path with a trailing /
when specifying the view, if you dont add the trailing slash it will try to find the path you specified in the render method inside the
views/site
directory and adding a trailing slash will search from the views
root directory.
Upvotes: 2
Reputation: 9402
Yii2 view paths are relative to the controller as @Saberi mentioned. Have a look at the docs
If the view name starts with a single slash /, the view file path is formed by prefixing the view name with the view path of the currently active module. If there is no active module, @app/views/ViewName will be used. For example, /user/create will be resolved into @app/modules/user/views/user/create.php, if the currently active module is user. If there is no active module, the view file path would be @app/views/user/create.php.
So the best thing is to create a BlogController, however if you really need to, you can achieve this by rendering from the SiteController via $this->render('/blog/index')
-- again, not really recommended -- or even by calling/redirecting to BlogController from SiteController, which also can get messy, but possible.
Upvotes: 0
Reputation: 7240
Yii2 sets the view directory to controllers based on their names match. So you can have a controller named BlogController and then simply render the index view:
class BlogController extends Controller
{
...
public function actionBlog() // OR public function actionIndex()
{
// not working
return $this->render('index');
}
}
Upvotes: 0