Search code examples
razordotnetnuke2sxc

How can I use Render sub-template in a C# template in a Content module that uses lists within lists?


2SXC 10.25.2 / DNN 9.3.2

I have a 2sxc module that uses a C# template with "list" enabled. I have a content type called "pathway" and inside that I have 2 entity picker fields for "first step sessions" and then "next step sessions". These entity pickers use a "session" content type. Inside each of those "session" content types I also have an entity picker for "speaker(s)". All in all, it's a setup that I have lists within lists within lists.

When I create the loops for each of the sublists, I can easily do that within the 1 C# template but it becomes repetitive, long, and unruly because there's so much c# code where I'm looping the same session template for different entity picker sections. So, I tried using the "Render sub-template" code to simplify the template - I created new sub templates and inserted them in - it seemed to work at first, however, the template started outputting all "session" items into each item in the list.

I suspect that the subtemplate somehow loses the context of the item that it's in so it's outputting everything. Is there something special I need to know about using subtemplates with for each loops? Do I have to include params and, if so, how do I do that?

EDIT to include code sample:

Here is a small, simplified version of the code I'm working with:

@foreach(var Content in AsList(Data)) {
<h2>@Content.Title</h2>
    
    <h3>Lead Sessions</h3>
    
    <div class="lead-sessions text-green">
        @foreach(var item in AsList(Content.LeadSessions as object)){
            <h4>@item.LeadSessionTitle</h4>
            <p>@item.LeadSessionText</p>
        }
    </div>    
        
    <h3>Next Sessions</h3>
    <div class="next-sessions text-green">
        @foreach(var nextitem in AsList(Content.NextSessions as object)){
            <h4>@nextitem.LeadSessionTitle</h4>
            <p>@nextitem.LeadSessionText</p>
        }
    </div>
}

I want to make a subtemplate so I don't have to repeat the same code for the sessions loop. How could I simplify this template to use a subtemplate for looping the sessions within the lead-sessions and next-sessions?


Solution

  • So based on the modified question, it's a bit like this

    @foreach(var Content in AsList(Data)) {
        <h2>@Content.Title</h2>
        
        <h3>Lead Sessions</h3>
        @RenderPage("_inner.cshtml", new { Items = Content.LeadSessions })
            
        <h3>Next Sessions</h3>
        @RenderPage("_inner.cshtml", new { Items = Content.NextSessions })
    }
    

    Second file _inner.cshtml

    @{
      var items = AsList(PageData["Items"]);
    }
    <div class="next-sessions text-green">
        @foreach(var nextitem in items){
            <h4>@nextitem.LeadSessionTitle</h4>
            <p>@nextitem.LeadSessionText</p>
        }
    </div>