Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Ben John Bagley 16 posts 146 karma points
    Oct 13, 2018 @ 21:59
    Ben John Bagley
    0

    Only show three records on partial

    Hi,

    So I have a blog partial

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    
    @{
      var selection = Model.Content.Site().FirstChild("blogPage").Children("blogPost").Where(x => x.IsVisible());
    }
    
    @foreach(var item in selection){
      <div class="blog-post">
        @{
          var mainPostImage = Umbraco.TypedMedia(item.GetPropertyValue<int>("mainPostImage"));
            if (mainPostImage != null)
            {
              <img src="@mainPostImage.Url" />
            }
          }
        <div class="container-inner" style="margin-top: -4px;">
          <a href="@item.Url">
            <h3>@item.Name</h3>
          </a>
          @Umbraco.Truncate(item.GetPropertyValue<string>("blogContent"), 200)
        </div>
      </div>
    }
    

    and I'm rendering the partial like this @Html.Partial("ListBlogItems") both on the index and the blogs page, however, I want to show three blog posts on the index and show all records on the blog page.

    So is there a way to limit the partial on the index to only render three records?

  • Thomas Morris 35 posts 133 karma points MVP c-trib
    Oct 14, 2018 @ 12:58
    Thomas Morris
    1

    Hey Ben,

    From your selection query, what you've got is a List in C# so you can use LINQ to filter the output.

    So selection.Take(3) will achieve what you are after, but then you won't be able to re-use the partial. What you can do is pass the collection of items to the partial and then iterate through those as you have done.

    Example for that: @Html.Partial("ListBlogItems", blogItems) where you instantiate blogItems beforehand. That will mean your model in the partial is now the blog items you passed in and you'll need to update the @inherits statement to match.

    e.g. @inherits Umbraco.Web.Mvc.UmbracoTemplatePage<IEnumerable<IPublishedContent>>

    The other thing to be aware of is that if you are already on the blog listing page then @Model.Content.Children("blogPost") will give you the blog pages anyhow and so is a more performant query as you're not traversing the content tree as much.

Please Sign in or register to post replies

Write your reply to:

Draft