Answer the question
In order to leave comments, you need to log in
How to check if a view exists in yii2?
$model = Page::find()->where(['url' => $page])->one();
return $this->render('$model->url', [
'model' => $model,
]);
Answer the question
In order to leave comments, you need to log in
1. quotes around $model->url must be removed otherwise it will never work
2. :
if( file_exists(Yii::getAlias('@frontend').'/views/mydir'.$model->url.'.php')){
$view = $this->render($model->url, [
'model' => $model,
]);
}else{
$view = $this->render('default', [
'model' => $model,
]);
}
return $view;
Here it is necessary to check for the existence of the model, not the view.
Write a function.
...
use yii\base\ViewNotFoundException;
...
$get = Yii::$app->request->get();
$path = Yii::getAlias('@web').'/views/mydir/'.$get['url'];
...
try {
// 1) тут пишите то что хотите проверить
$this->render($path, ['model' => $model,]);
} catch (ViewNotFoundException $e) {
// 2) тут выводите "удобную" ошибку, чтобы не закрывать ошибкой 500 или той которая вылезает
$this->render('default', [ 'model' => $model,]);
}
...
Yii::getAlias('@frontend')
- what if the project is not in the folder frontend
??? return $view;
Either you get a view, or default Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question