Extending TBBs with a Custom Model Builder

Use the DXA Model Builder architecture to extend Template Building Blocks (TBBs). The architecture makes it easy to add to or enrich your page and entity models without creating a completely new TBB.

Appending a custom Model Builder

You can extend both page and entity models by implementing either the following interfaces:

  • IPageModelDataBuilder
  • IEntityModelDataBuilder

To extend an existing Template Building Block, add the name of your custom Model Builder class to the list in the modelBuilderTypeNames parameter.

Sample Model Builder: Add extra information to a DXA data model object

The following sample code illustrates how you can use the Model Builder Pipeline to create DXA data models from content management items. This sample Model Builder for pages adds trackingKeyCondition (tracking keyword conditions), which are used for each component presentation. This code would result in a new object named KeywordCondition being added to the ExtensionData of the Page Model.

public enum ConditionOperator
{
    UnknownByClient = -2147483648,
    Equals = 0,
    GreaterThan = 1,
    LessThan = 2,
    NotEqual = 3,
}
 
public class KeywordCondition
{
    public KeywordModelData KeywordModelData { get; set; }
    public ConditionOperator Operator { get; set; }
    public object Value { get; set; }
    public bool Negate { get; set; }
}
 
public class AddTrackingModelBuilder : DataModelBuilder, IPageModelDataBuilder
{
    public AddTrackingModelBuilder (DataModelBuilderPipeline pipeline) : base(pipeline)
    {
    }
 
    public void BuildPageModel(ref PageModelData pageModelData, Page page)
    {
        pageModelData.ExtensionData.Add("KeywordConditions", (
        from trackingKeyCondition in (
            from componentPresentation in page.ComponentPresentations
            where componentPresentation.Conditions != null
            from condition in componentPresentation.Conditions
            from c in condition.TargetGroup.Conditions select c).OfType<TrackingKeyCondition>()
                let keywordModelData = Pipeline.CreateKeywordModel(trackingKeyCondition.Keyword, Pipeline.Settings.ExpandLinkDepth)
                let op = (ConditionOperator) trackingKeyCondition.Operator
                let negate = trackingKeyCondition.Negate
                let value = trackingKeyCondition.Value
                select new KeywordCondition
                {
                    KeywordModelData = keywordModelData, Operator = op, Value = value, Negate = negate
                }).ToArray());
        }
}

To use the sample snippet, create or edit an existing page template and add the name AddTrackingModelBuilder to the modelBuilderTypeNames parameter (provided by the Generate DXA R2 Page Model TBB).

For complete information on using the Tridion Sites Template Builder, refer to the Tridion Sites product documentation.