Search code examples
model-view-controlleryii2yii2-module

Yii2: Render module view from main application


How can a Yii2 application Controller (not a module controller) render a view that is provided by a module, assuming the module follows the directory structure outlined in the documentation?


Solution

  • As mentioned in method render() you can specify view as:

    • path alias (e.g. "@app/views/site/index"); absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual view file will be looked for under the view path of the application.
    • absolute path within module (e.g. "/site/index"): the view name starts with a single slash. The actual view file will be looked for under the view path of $module.
    • relative path (e.g. "index"): the actual view file will be looked for under $viewPath.

    So in the case of the module mentioned by you do this in the action:

    return $this->render('@app/modules/forum/views/default/index');
    

    This will render the view with applied layout of the main application. To use module's layout add this as well in the action:

    $this->layout = '@app/modules/forum/views/layouts/main';
    

    This assumes view default/index and layout main in the forum module.