How to get objects in a razor template in Tridion?

1.2k Views Asked by At

I am writing a common Razor TBB, which will use in Component Template and Page template as per my requirement.

So that, I need a Page and Component object in the razor TBB according to applying TBB on Page Template and component Template

My requirement to display/use the metadata field values from Page/Component in specific area of the page.

That's why, i want to access metadata values by the object but unable to get the object,

Please also follow-up my comments with Frank.

Can any one suggest me?

1

There are 1 best solutions below

6
On

Did you have a look at the (remarkably helpful) documentation that is available for the Razor mediator?

These are full of examples that access the current Component and the Page. Just my 10 second search gives these fragments:

<body class=”@Page.Metadata.BodyClass”>

<div class=”@Component.Fields.NewsStyle”>

<img src=”@Fields.HeaderImage.ID” alt=”@Fields.HeaderImage.AltText” />

Edit: I see you added some more details in your follow-up comment. You might want to do as Bart suggests and add those details to the question. In the meantime, I'll spend a few more minutes searching the documentation for you.

The official documentation (the Word document I linked above), contains this example that seems to process metadata:

@foreach (var keyword in Publication.MetaData.SomeKeywordFields) {
    <li>@keyword.Title (@keyword.Id)</li>
}

The output of the Razor template will become the Output item in the Package. So it doesn't make any sense to use a Razor mediator to process the Output item. For that you might as well use a regular C# (fragment or assembly) TBB.

Another edit: It seems that the Razor mediator's implicit Fields variable always maps to the Component fields and the Metadata variable always maps to the Component's meatadata fields. I've linked the above names to the relevant fragments on Google code for your convenience.

So you seem to have two options:

  1. detect whether you are in Page or Component (e.g. by looking at whether the implicit Page variable is null or not) and then have conditional expressions everywhere (isInPage ? Page.Metadata : Metadata)
  2. fix this limitation of the Razor mediator code yourself or hire someone to fix it for you