Documentation Center

Accessing specific Component Presentations on a Page

If the Component Presentations on a Page are not assembled at visit time using a query, the Page contains a list of Component Presentations (pairs of a Component and its accompanying Component Template). You can access specific Component Presentations on a Page item inside a package, or on a Page in the Content Manager.

Package example

The package that is processed by a Compound Page Template initially only contains a Page item. To get to the Component Presentations on the Page, use the default Template Building Block called "Extract Components from Page". This adds a Components array to the package, containing the Component Presentations.

The following code sample shows you how to access only those Component Presentations on a Page that have a specific Component Template.

// Get the Components array. ComponentsName is a constant for the string "Components".
Item componentsItem = package.GetByName(ComponentsName);

IComponentPresentationList componentPresentations =
	ComponentPresentationList.FromXml(componentsItem.GetAsString());

// Loop through the CPs and remove all Component Presentations that have a Component Template
// other than tcm:13-60-32.
foreach (Tridion.ContentManager.Templating.ComponentPresentation
	componentPresentation in componentPresentations)
{
	TcmUri allowedTemplateURI = new TcmUri("tcm:13-60-32");
	if (componentPresentation.TemplateUri.Equals(allowedTemplateURI))
	{
		componentPresentations.Remove(componentPresentation);
	}
}

// Modify the Components item to now contain this new array.
componentsItem.SetAsString(ComponentPresentationList.ToXml(componentPresentations));

Content Manager example

In the Content Manager, you have direct access to the Component Presentations from a Page object. The following code sample shows you how to count those Component Presentations on a Page that have a Component Template called Summary.

string pageURI = package.GetValue("Page.ID");
Page page = (Page)engine.GetSession().GetObject(pageURI);
int summaryCounter = 0;
// Loop through the CPs and count all Component Presentations
// that have a Component Template called "Summary"
foreach (Tridion.ContentManager.CommunicationManagement.ComponentPresentation
	componentPresentation in page.ComponentPresentations)
{
	if (componentPresentation.ComponentTemplate.Title.Equals("Summary"))
	{
		summaryCounter++;
	}
}
log.Info("Page contains " + summaryCounter + " Components displayed as summaries.");