Yii2 在视图文件夹范围内创建和使用变量
Yii2 Create & use variable with views folder scope
我正在尝试创建一个 Yii2 主题,并且想设置一个范围为整个 views 文件夹的变量。对于我使用的单页主题...
$assetDir = Yii::$app->assetManager->getPublishedUrl(
'@vendor/path/to/assets/folder'
);
在 index.php
& 然后我使用...
访问它
<img src="<?= $assetDir ?>/img/image.jpg" alt="">
对于部分,我可以使用...
<?= $this->render('_partial.php', ['assetDir' => $assetDir]) ?>
我现在想在具有多个页面的主题中做类似的事情,如果不在每个页面中设置 $assetDir
就找不到如何做到这一点。我想它将设置在 main.php
布局中。
如 Sharing Data among Views 所述,为此使用 params
数组。
The view component provides the params property that you can use to share data among views.
For example, in an about view, you can have the following code which specifies the current segment of the breadcrumbs.
$this->params['breadcrumbs'][] = 'About Us';
Then, in the layout file, which is also a view, you can display the breadcrumbs using the data passed along params:
<?= yii\widgets\Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
我正在尝试创建一个 Yii2 主题,并且想设置一个范围为整个 views 文件夹的变量。对于我使用的单页主题...
$assetDir = Yii::$app->assetManager->getPublishedUrl(
'@vendor/path/to/assets/folder'
);
在 index.php
& 然后我使用...
<img src="<?= $assetDir ?>/img/image.jpg" alt="">
对于部分,我可以使用...
<?= $this->render('_partial.php', ['assetDir' => $assetDir]) ?>
我现在想在具有多个页面的主题中做类似的事情,如果不在每个页面中设置 $assetDir
就找不到如何做到这一点。我想它将设置在 main.php
布局中。
如 Sharing Data among Views 所述,为此使用 params
数组。
The view component provides the params property that you can use to share data among views.
For example, in an about view, you can have the following code which specifies the current segment of the breadcrumbs.
$this->params['breadcrumbs'][] = 'About Us';
Then, in the layout file, which is also a view, you can display the breadcrumbs using the data passed along params:
<?= yii\widgets\Breadcrumbs::widget([ 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ]) ?>