我需要将谷歌标签管理器(Gtag)添加到项目的所有页面(模块)中。Gtag-code 由 3 个文件组成:
- 2 files with js-code, that needs to be included in <head> tag,
- 1 file with <noscript> tags that need to be included in <body> tag.
我项目的每个模块都包含layout.php
和AppAsset.php
. 这些布局中的 .js 文件需要包含在<body>
标签中。
所以,我创建了GlobalAppAsset.php
,$js
在那里定义了-property:
class GlobalAppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/gtag_script1.js',
'js/gtag_script2.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
}
AppAsset.php
对于我继承的项目中的每个模块,GlobalAppAsset.php
现在我需要将其$js
与$js
.property 中的 -property合并GlobalAppAsset.php
。我怎样才能正确地做到这一点?
另外,我需要将AppAsset.php
的 js 文件包含在<body>
布局的 -section 中,并将GlobalAppAsset.php
的 $js 文件包含在<head>
-section 中。我怎么能这样
最后,我需要将 Gtag 的 php 文件与<nonscript>
-part of gtag in <body>
. 可以用资产来做吗?
在您的情况下,最好$depends
在 AppAsset 中使用属性而不是扩展 GlobalAppAsset。
您可以保持 GlobalAppAsset 不变,AppAsset 应如下所示:
class AppAsset extends AssetBundle
{
//... other app assets configuration
public $jsOptions = ['position' => \yii\web\View::POS_BEGIN];
public $depends = [
//... some other dependencies
\fully\qualified\GlobalAppAsset::class
];
}
至于包含 noscript 片段,资产不是如何做到这一点的最佳方式。可能有一些方法,例如覆盖register()
注册方法,yii\web\View::EVENT_BEGIN_BODY
然后在注册的事件处理程序中输出代码片段。
class GlobalAppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/gtag_script1.js',
'js/gtag_script2.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
public static function register($view) {
parent::register($view);
$view->on(
\yii\web\View::EVENT_BEGIN_BODY,
function($event) use ($view) {
echo $view->render('the-view-with-noscript');
}
)
}
}
此解决方案可能有效,但由于此解决方案并不完全标准,因此可能会导致以后维护代码出现问题。
更好的解决方案是使用小部件,但您需要在每个布局文件中运行小部件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句