5

I'm using Razor templates and I've defined a variable in the page templates. How can I used the variable in the component template using razor?

In my Razor template I have:

@{
    string hotelTCM = @Package.Hotel_ID;
}

How can I use it in a embbeded component template?

2
  • Are you talking about a variable defined in your Razor template? Something on the package? A metadata field...? Clarify your question.
    – Ant P
    Commented Feb 20, 2014 at 19:12
  • Please update your question with your code, screenshots, etc. Commented Feb 20, 2014 at 19:13

2 Answers 2

3

Package variables (and the package instance) are independent to the Template item, meaning a package variable from a Page Template will not be available to a Component Template, since the latter has its own package instance.

If you want to pass variables between Templates (Page -> Component) you can use a ContextVariable, see also https://code.google.com/p/tridion-practice/wiki/PassContextFromOneComponentRenderToAnother

// in your Page Template
...
engine.PublishingContext.RenderContext.ContextVariables.Add("contextBag", contextBag);

and

// in your Component Template
...
var contextBag = (Dictionary<string, object>)engine.PublishingContext.RenderContext.ContextVariables["contextBag"];

update

I have to add, this is the case for the Modular Templating Framework using DWT TBBs, I'm not a 100% sure this also counts for the Razor Mediator which you are using.

2

You can use it by writing the following in your template.

if(!string.IsNullOrEmpty()) {
    <p>@hotelTCM</p>
}

More information is in the documentation;

@{
    int x = 123;
    bool test = true;
    string y = "because.";
    var greeting = "Hello";
}

<div>@greeting</div>
<div>@(test ? y : greeting)</div>
2
  • This works if I use the variable in the same page template. But If I try to use it in a embbeded component template doesn't work. Actually, I can save the razor component template because it doesn't interpret @*hotelTCM. I've tried @*Package.Hotel_ID and didn't work...
    – Aroma
    Commented Feb 21, 2014 at 9:30
  • Please provide more information about what you want to achieve what you have and have done
    – user219
    Commented Feb 21, 2014 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.