Filtering out based upon Type

I’m trying to generate some code only on pages of a specific type - but I’m having a problem when I try to test for the value of .Type, as it’s optional, and just checking for it seems to blow up on pages that don’t have it set (i.e., the index page, etc).

Here’s the partial:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', '{{ .Site.GoogleAnalytics }}', 'auto');
  ga('send', 'pageview');

{{ if .Type }}


  {{ $path := split $.Source.File.Path "/" }}
  {{ $event_slug := index $path 1 }}
  {{ $e :=  (index $.Site.Data.events $event_slug) }}

  <!-- hello world -->
  <!-- my type is {{ print .Type }} -->
  {{ if isset $e "ga_tracking_id" }}

  ga('create', '{{ $e.ga_tracking_id }}', {'name':'{{ print $event_slug }}'});
  ga('send', 'pageview');

  {{ end }}
{{ end }}

</script>

And I get this type of error:

ERROR: 2016/08/28 16:31:55 template.go:131: template: theme/partials/googleanalytics.html:10:6: executing "theme/partials/googleanalytics.html" at <.Type>: Type is not a field of struct type *hugolib.Node in theme/partials/googleanalytics.html

any ideas?

Unlike pages with content a node doesn’t have a type. Therefore, you can’t access the type on a node with <!-- my type is {{ print .Type }} -->.

You could check with {{ if .IsPage }} if the current site is a page. Pages have a .Type so you should be save to print the type.

1 Like