This article does not cover the creation of a Google Analytics account, property or stream, So I am assuming you have already created these items.
The solution I am implementing here is to create a partial view called frontend/views/layouts/_google-analytics.php
, which is called in the header element of the main layout page frontend/views/layout/main.php
. The partial view is only loaded if a google-measurement-id
custom parameter has been specified.
Main Layout View
Line 13-15 load the partial view if a google-measurement-id
exists:
frontend/views/layouts/main.php
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php $this->registerCsrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php
$measurementId = Yii::$app->params['google-measurement-id'] ?? null;
if ($measurementId)
echo $this->render('/layouts/_google-analytics', ['measurementId' => $measurementId]);
$this->head();
?>
</head>
<body>
<?php $this->beginBody() ?>
Google Analytics Partial View
This is the JavaScript injected into the HTML header element of the main layout.
frontend/views/layouts/_google-analytics.php
<?php
/**
* View template for google analytics JavaScript
*
* @var string $measurementId
*
*/
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?=$measurementId?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<?=$measurementId?>');
</script>
Params File
Our params files contains the Google Analytic Stream Measurement ID.
environments/prod/frontend/config/params-local.php
<?php
return [
'google-measurement-id' => 'G-***PROD***',
];
environments/dev/frontend/config/params-local.php
<?php
return [
'google-measurement-id' => 'G-****DEV***',
];
Remember, for our local param values to take effect, you will need to run the Yii php init
script from your application console.