wangming1993 / issues

记录学习中的一些问题,体会与心得 https://wangming1993.github.io/issues
8 stars 4 forks source link

Yii2 controller中如何设置layout和view的路径 #23

Open wangming1993 opened 8 years ago

wangming1993 commented 8 years ago

Yii2 controller中如何设置layout和view的路径

yii\base\View中的 findViewFile($view, $context = null) 中 存在 5view的处理方式:

if (strncmp($view, '@', 1) === 0) {
    // e.g. "@app/views/main"
    $file = Yii::getAlias($view);
} elseif (strncmp($view, '//', 2) === 0) {
    // e.g. "//layouts/main"
    $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
} elseif (strncmp($view, '/', 1) === 0) {
    // e.g. "/site/index"
    if (Yii::$app->controller !== null) {
        $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
    } else {
        throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
    }
} elseif ($context instanceof ViewContextInterface) {
    $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
} elseif (($currentViewFile = $this->getViewFile()) !== false) {
    $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
} else {
    throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
}

yii\base\Controller中的 findLayoutFile($view) 中 存在 3layout的处理方式:

if (strncmp($layout, '@', 1) === 0) {
    $file = Yii::getAlias($layout);
} elseif (strncmp($layout, '/', 1) === 0) {
    $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
} else {
    $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
}