I am working on adding data tracking attributes to some components so we can gather data on usage of the different personalized blades on each page. Is there a way to programmatically access the name for the currently rendered Personalization Condition on a page? That would be the circled value in the image below:
In Sitecore Rendering
or Final renderings
fields contains personalization ruleset. you can open an item and can check the Raw value of the field, you will see something like this in the field -
<r uid="{6C8B4F92-7B6F-411F-B024-EA0E2CE80C23}"><rls><ruleset><rule uid="{7537D280-20C4-4D44-AAAC-6F01F334ACF4}" s:name="persona"><conditions><condition uid="1CDF85B60D64456FAEC9FC13C7EE7AE1" s:id="{E00DB4F0-B206-4544-AD90-25D201CFB62C}" s:ProfileName="UTA" s:PatternName="Freshman Student" /></conditions><actions><action uid="F0E9E6238A664DD4A33CBFD8C839D563" s:id="{25F351A1-712D-45F8-857D-8AD95BB2ACE9}" /></actions></rule><rule uid="{00000000-0000-0000-0000-000000000000}" s:name="Default"><conditions><condition uid="9160BAF079E54DA98B3F58137B026051" s:id="{4888ABBB-F17D-4485-B14B-842413F88732}" /></conditions><actions /></rule></ruleset></rls></r>
The personalization rules value is set on the field with an XML format and you need to do get renderings with personalization rule set on it as the first part of your code -
var item = Sitecore.Context.Item;
Sitecore.Data.Fields.LayoutField layoutField = item.Fields["__renderings"];
Sitecore.Layouts.RenderingReference[] renderings = layoutField.GetReferences(Sitecore.Context.Device);
var renderingsWithPersonalization = renderings.Where(r => r.Settings.Rules.Count > 0).ToList();
in above code .Where(r => r.Settings.Rules.Count > 0)
will give only the renderings that contain personalization rules.
Next part is knowing the Personalization Rule by creating a ConditionalRenderingsRuleContext
with the renderings in the page and the rendering that contains the personalization rule, and by invoking the rule.Evaluate(ruleContext)
-
List rulesName = new List();
foreach (var rendering in renderingsWithPersonalization)
foreach (var rule in rendering.Settings.Rules.Rules)
{
var ruleContext =
new Sitecore.Rules.ConditionalRenderings.ConditionalRenderingsRuleContext(
renderings.ToList(), rendering);
if (rule.Evaluate(ruleContext))
rulesName.Add(rule.Name);
}
In the above code, rulesName
will contain all the rule that is currently being used on the page