Developer forum

Forum » Templates » Include/IncludeFile inside item template

Include/IncludeFile inside item template

Martin Grønbekk Moen
Reply

So I'm wondering if this is even possible. I have a wish that goes something like this.

My general thought is to use items for all that it is worth, and I would also like to reuse items inside other items.
I have three items, and the are setup like this.

  • Banner Container
    • Title (text)
    • Banners (Item relation list <Banner>)
  • Banner
    • Text (Text)
    • Image (File)
    • Button (Item type <Button>)
  • Button
    • Text (Text)
    • Link (Link)

This works out just fine, no problem with the setup. I have also created one template for "Banner Container" where I currently have all my code.
I loop through the list of banners, show them and also show my button. This actually is okay, but I want to improve this setup.

My issue is with the "Button". I would really like to use this item type in other items, and I would really like to maintain my code for the button in one place only.
So my thought was to create a new razor file for my button "Button.cshtml" where I put all my button specific code. Then I would like to use Include/IncludeFile where needed, ex. in my "Banner Container" template. I tried this, but it gave me a lot of issues with razor.

Does anyone have examples of how this can be done, pelase point me in the right direction :)


Replies

 
Nicolai Høeg Pedersen
Reply

Hi Martin

You might want to take a look at Razor helpers. They are made for the purpose you ask for. Inside a template you define these Helper methods that can be used from other places. Then just include the razor file with the helper files once and you can call it multiple times.

You can make a setup someting like this:

Button.cshtml

@helper Button(string name, string action)
{
    <a href="@action" class="btn">@name</a>
}

Banner.cshtml
@Include("Button.cshtml")
@{
    var buttonName = GetValue("Item.ButtonName");
    var buttonAction = GetValue("Item.ButtonAction");

    var button2Name = GetValue("Item.Button2Name");
    var button2Action = GetValue("Item.Button2Action");
}
<h1>@BannerName</h1>
@Button(buttonName, buttonAction)
<div>
@GetValue("Item.Text");
</div>

@Button(button2Name, button2Action)

 

You must be logged in to post in the forum