Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions analytical/templatetags/google_analytics_gtag.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"""

GTAG_SET_CODE = """gtag('set', {{'{key}': '{value}'}});"""

GTAG_EVENT_CODE = """gtag('event', {key}, {value});"""
register = Library()


Expand Down Expand Up @@ -61,9 +61,12 @@ def render(self, context):
if identity is not None:
other_fields['user_id'] = identity

extra = '\n'.join([
commands = [
GTAG_SET_CODE.format(key=key, value=value) for key, value in other_fields.items()
])
]
commands += self._get_event_commands(context)

extra = '\n'.join(commands)
html = SETUP_CODE.format(
property_id=self.property_id,
extra=extra,
Expand All @@ -72,6 +75,24 @@ def render(self, context):
html = disable_html(html, 'Google Analytics')
return html

def _get_event_commands(self, context):
values = (
context.get('google_analytics_event%s' % i) for i in range(1, 6)
)
params = [(i, v) for i, v in enumerate(values, 1) if v is not None]
commands = []
for _, var in params:
key, value = var
try:
dict(value)
except ValueError:
value = f"'{value}'"
Comment on lines +86 to +89
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't look like a valid pattern. The try-block shouldn't be use for testing on a data type. And what's code in the except-clause? I think this is an edge case of a "pythonic try-except" where the pattern doesn't fit.

It's not clear at first sight what we're trying to achieve. Maybe an if instanceof(value, dict) would be better here, because it's more explicit for the use case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you be interested to fix the code issue, so we can merge the changes?

commands.append(GTAG_EVENT_CODE.format(
key=key,
value=value,
))
return commands


def contribute_to_analytical(add_node):
GoogleAnalyticsGTagNode() # ensure properly configured
Expand Down