What is the simplest way to find current item ID in the template
Asked Answered
C

2

5

In my C# or dreamweaver template I need to know what am I rendering. The problem is that I don't know for sure if I'm looking for a page or component. I could probably use package.GetByType(ContentType.Page) and if it's empty - get content of a component, but I feel there should be a shorter way.

Example of David is shorter:

engine.PublishingContext.ResolvedItem.Item.Id
Crankshaft answered 11/2, 2013 at 9:39 Comment(0)
H
5
engine.PublishingContext.ResolvedItem.Item.Id

You can also check the Publishing Context's resolved Item and see if it's a Page or not (if it's not, then it's a Component).

For example:

Item currentItem;
if (engine.PublishingContext.ResolvedItem.Item is Page)
{
    currentItem = package.GetByName(Package.PageName);
}
else
{
    currentItem = package.GetByName(Package.ComponentName);
}
TcmUri currentId = engine.GetObject(currentItem).Id;

If you want to shortcut the engine.GetObject() call, then you may be able to get the ID from the Item's XML directly:

String currentId = currentItem.GetAsSource().GetValue("ID");
Humidistat answered 11/2, 2013 at 12:2 Comment(1)
That's much nicer than my approach.Leporide
L
3

That's how I've seen it done before:

// Contains the call you describe in your question
Page page = GetPage(); 
if (page == null)
{
    // Contains a call using package.GetByName("Component") 
    // to avoid the situation with multiple Components on the package
    Component comp = GetComponent();
    // Do component stuff
}
else
{
    // Do page stuff
}

Not sure you can encapsulate it much nicer than that really but I may be proved wrong.

Leporide answered 11/2, 2013 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.