MVC views
Within an MVC view, you may have conditional logic that controls what markup the view exposes. A common example is a view that includes third-party trackers only if the visitor has accepted a privacy policy.
With traditional Sitecore, this logic might be hard-coded into the view using C# code. That C# code will not run when Uniform is used to decouple delivery from the Sitecore CD instance.
Uniform provides a way to create conditional blocks that are compatible with the supported personalization engines (e.g. edge-based personalization engine) without you having to write code that targets a specific personalization engine.
#
ExampleThe example in this section demonstrates how to programmatically change the markup exposed by a view depending on which rule matches the visitor's context. Imagine a case where you want to display a pricing discount based on the business relationship the visitor has with your brand ("customer type"):
- Wholesalers see 45% discount
- Retailers see 10% discount
- Premium retailers see 12% discount
- Everyone else sees 5% discount
#
Define rulesRules are needed to define the conditions that determine the visitor's customer type. When a visitor logs into the site, a cookie is set that identifies the visitor's customer type:
- If the cookie
CT
has a value ofW
, the visitor is a wholesaler. - If the cookie
CT
has a value ofR
, the visitor is a retailer. - If the cookie
CT
has a value ofP
, the visitor is a premium retailer. - If the cookie
CT
has any other value, or if the cookie doesn't exist, the visitor's customer type is unknown.
- In Sitecore, open Marketing Control Panel.
- Navigate to Personalization > Predefined Rules.
- Add a new item using the template Conditional Rendering Rule.
- Add a condition that checks if the cookie
CT
has a value ofW
. - Note the item id. This is the id of the condition that determines the visitor is a wholesaler.
- Repeat these steps for the retailer and premium retailer customer types.
#
Add conditional blocks to viewAdd the following code to your view:
@Html.Uniform().RenderConditionalBlock(initialize =>{ const string WHOLESALER_CONDITION_ID = ""; const string RETAILER_CONDITION_ID = ""; const string PREMIUM_RETAILER_CONDITION_ID = ""; initialize.If(WHOLESALER_CONDITION_ID, @<div>45% discount</div>); initialize.ElseIf(RETAILER_CONDITION_ID, @<div>10% discount</div>); initialize.ElseIf(PREMIUM_RETAILER_CONDITION_ID, @<div>12% discount</div>); initialize.Else(@<div>5% discount</div>);})
For the constant
WHOLESALER_CONDITION_ID
, set the condition id from the previous section.For the constant
RETAILER_CONDITION_ID
, set the condition id from the previous section.For the constant
PREMIUM_RETAILER_CONDITION_ID
, set the condition id from the previous section.