E
E
Evgeny Kylin2016-12-19 19:39:53
Yii
Evgeny Kylin, 2016-12-19 19:39:53

How to check if a view exists in yii2?

$model = Page::find()->where(['url' => $page])->one();
        return $this->render('$model->url', [
            'model' => $model,
        ]);

How to check if a view exists, and if not, then open the default "view"?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Timofeev, 2016-12-19
@palkan_karabov

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;

M
melnikov_m, 2016-12-19
@melnikov_m

Here it is necessary to check for the existence of the model, not the view.

I
Igor Vasiliev, 2019-07-09
@Isolution666

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,]);
}
...

You can also contact Yii::getAlias('@frontend')- what if the project is not in the folder frontend???
So no return $view;Either you get a view, or default
ViewNotFoundException keeps track of this, I abandoned file_exists in Yii a long time ago because it is not efficient and does not work, yes, if there is a file, errors will not come out, and if there is no file, you will encounter ViewNotFoundException
So why not immediately catch the error and just display it as text on the page?
Much better than a full page error.
Well, is it Easy? Truth? :)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question