OSDN Git Service

Add Plugin::GoogleAnalytics
authorhylom <hylom@users.sourceforge.jp>
Wed, 11 Oct 2017 07:51:11 +0000 (16:51 +0900)
committerhylom <hylom@users.sourceforge.jp>
Wed, 11 Oct 2017 07:51:11 +0000 (16:51 +0900)
src/newslash_web/lib/Newslash/Plugin/GoogleAnalytics.pm [new file with mode: 0644]
src/newslash_web/lib/Newslash/Web.pm
src/newslash_web/templates/common/analytics.html.tt2 [new file with mode: 0644]
src/newslash_web/templates/common/header.html.tt2

diff --git a/src/newslash_web/lib/Newslash/Plugin/GoogleAnalytics.pm b/src/newslash_web/lib/Newslash/Plugin/GoogleAnalytics.pm
new file mode 100644 (file)
index 0000000..3f1351b
--- /dev/null
@@ -0,0 +1,18 @@
+package Newslash::Plugin::GoogleAnalytics;
+use Mojo::Base 'Mojolicious::Plugin';
+
+sub register {
+    my ($self, $app, $conf) = @_;
+
+    $self->{conf} = {%$conf, %{$app->config->{Analytics}}};
+    $self->{app} = $app;
+
+    if ($app->config->{TT2Renderer}) {
+        my $tt2r = $app->config->{TT2Renderer}->{self};
+        $tt2r->add_object(Analytics => $self->{conf});
+    }
+
+    $app->helper(google_analytics => sub { state $google_analytics = $self; });
+}
+
+1;
index 9a66a6e..2a3b45d 100644 (file)
@@ -74,6 +74,9 @@ sub startup {
     # use Template::Toolkit 2 render
     $app->plugin('Newslash::Plugin::TT2Renderer');
 
+    # use Analytics helper
+    $app->plugin('Newslash::Plugin::GoogleAnalytics');
+
     # user AntiCsrf ($app->anti_csrf)
     if ($app->mode ne 'test') {
         # when test mode, disable AntiCsrf.
diff --git a/src/newslash_web/templates/common/analytics.html.tt2 b/src/newslash_web/templates/common/analytics.html.tt2
new file mode 100644 (file)
index 0000000..3a43062
--- /dev/null
@@ -0,0 +1,12 @@
+[%- IF Analytics && Analytics.tag -%]
+<script async src="https://www.googletagmanager.com/gtag/js?id=[% Analytics.tag %]"></script>
+<script>
+  window.dataLayer = window.dataLayer || [];
+  function gtag(){dataLayer.push(arguments);}
+  gtag('js', new Date());
+
+  gtag('config', '[% Analytics.tag %]');
+</script>
+[%- ELSE -%]
+<!-- no Analytics.tag given -->
+[%- END -%]
index cc4adee..05eef7f 100644 (file)
@@ -1,4 +1,9 @@
 <head>
+  [%- IF NS.mojo_mode == "production" %]
+  [% INCLUDE common/analytics %]
+  [%- ELSE %]
+  <!-- running under [% NS.mojo_mode %] mode. -->
+  [%- END %]
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta name="viewport" content="width=device-width" />