Search code examples
phphtmllayoutyii2glyphicons

Yii2:how to use model's data in layouts


I want to add my database's data in layouts ,how to do it?thanks. I know the way such as $this->params['params'] = "params",but in function like beforeAction

  <div class="sBox">
            <div class="subNav sublist-down">
                <span class="title-icon glyphicon glyphicon-chevron-right"></span>
                <span class="sublist-title">资源管理</span>
            </div>
            <ul class="navContent" style="display:none">
                <li class="nav-li">
                    <div class="showtitle" style="width:100px;">
                        <img src="__ADMIN_IMAGES__/leftimg.png" />
                    </div>
                    <a href="<?= UrlService::buildWwwUrl('source/index'); ?>" target="right_content">
                        <span class="sublist-icon glyphicon glyphicon-record"></span>
                        <span class="sub-title">资源列表</span>
                    </a>
                </li>
            </ul>
        </div>

Solution

  • The question isn't quite clear. Show your layout and data which you want to use.

    Here are many different ways to use data in layout:

    • Using widgets. You can create own widget, it's simple
    • Using application components or application itself. For example \Yii::$app->params (you mentioned this in question)
    • Using $this variable (\yii\web\View), for example it's common practice to use $this->title which can be assigned in controller
    • Using View data. Layout have access to all params passed to view. This can be acceptable if you have some data format convention for all controllers

    Which of them is the right one for you depens on the problem you solve.