Personalization State For Tag Managers

There have often been clients of mine who have asked the question “how do we use Google Analytics to track the value of our personalization campaigns?”.  The first answer is usually that there isn’t a good way to do so, not built in anyway.  So we build something!  I’ve set up a static method to generate personalization stats for the current page and drops it in a meta-tag.  That way you can easily set up any tag management analytics tool to keep track of a user based on personalization states.

How it works

Every time a user sets up a block of rules to trigger a personalization state.  They give it a name, i propose that they use this name as a sort of campaign tag withing the tag manager.  Here’s an example of a block of rules.

personalizationform

Using the above highlighted name as the key value for this particular personalization block would allow us to generate a meta-tag that looks like this:

<meta name="personalizationState" content="Target User">

If multiple personalization states were to have been triggered their names would be added to the content of the meta-tag as a comma delimited list.

Show me the code

	public class PersonalizationState
	{
		public static string GenerateMetaTags()
		{
			StringBuilder sb = new StringBuilder();
			RuleStack stack = new RuleStack();
			var references = Sitecore.Context.Item.Visualization.GetRenderings(Sitecore.Context.Device, false);
			try
			{
				foreach (RenderingReference reference in references)
				{
					ConditionalRenderingsRuleContext context = new ConditionalRenderingsRuleContext(references.ToList(), reference);
					foreach (Rule<ConditionalRenderingsRuleContext> rule in reference.Settings.Rules.Rules)
					{
						rule.Condition.Evaluate(context, stack);
						if ((stack.Count != 0) && (bool) stack.Pop() && rule.UniqueId != ID.Null)
						{
							sb.Append(",").Append(rule.Name);
							break;
						}
					}
				}
			}
			catch (Exception e)
			{
				Log.Warn("Problem aggregating rules for personalization context, metatag may be incorrect", e, e);
			}
			return sb.Length > 0 ? $@"<meta name=""personalizationState"" content=""{sb.ToString(1, sb.Length - 1)}"">" : "";
		}
	}

It would then be utilized in your cshtml (or using similar techniques in aspx, if you’re into that sort of thing) like so.

@Html.Raw(PersonalizationState.GenerateMetaTags())