Frage

I have a page that has a child node named "Widgets". I want to render that child's template at a certain section in my page template. Currently, I do this:

@{
    foreach (var child in CurrentPage.Children)
    {
        if (child.Name == "Widgets")
        {
            @Umbraco.RenderTemplate(child.Id)
        }
    }
}

Is there a way to avoid having to loop through the children like this?

I've also discovered I can do this:

@{
    @Umbraco.RenderTemplate(
        Model.Content.Children
            .Where(x => x.Name == "Widgets")
            .Select(x => x.Id)
            .FirstOrDefault())
}

But I was really hoping there was a more terse way to do this, since I may want to do it in several places on a given page.

War es hilfreich?

Lösung

Yes, you could use Examine.

However, I would strongly object to this practice, because the user is able to change the Name of a node, and thus possibly breaking your code.

I would create a special document type and search the node using the document type. There are several (fast) ways to do that:

@Umbraco.ContentByXPath("//MyDocType") // this returns a dynamic variable
@Umbraco.TypedContentSingleByXPath("//MyDocType") // this returns a typed objects
@Model.Content.Descendants("MyDocType")
// and many other ways

Andere Tipps

Yes on the same Idea of accepted answer

Following code worked for me.

 var currentPageNode = Library.NodeById(@Model.Id);

  @if(@currentPageNode.NodeTypeAlias == "ContactMst")
   {
              <div>Display respective data...</div>
  }

As mention not good practice. Rather find nodes by their type and use the alias of the document type in your code. If for whatever reason you need a particular node, rather give it a property and look for the property. Sample code below

if (Model.Content.Children.Any())
{
    if (Model.Content.Children.Where(x => x.DocumentTypeAlias.Equals("aliasOfCorrespondingDocumentType")).Any())
    {
        // gives you the child nodes underneath the current page of particular document type with alias "aliasOfCorrespondingDocumentType"
        IEnumerable<IPublishedContent> childNodes = Model.Content.Children.Where(x => x.DocumentTypeAlias.Equals("aliasOfCorrespondingDocumentType"));

        foreach (IPublishedContent childNode in childNodes)
        {
            // check if this child node has your property
            if (childNode.HasValue("aliasOfYourProperty"))
            {
                // get the property value
                string myProp = childNode.aliasOfYourProperty.ToString();

                // continue what you need to do
            }
        }
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top