Get number of components in placeholder, Sitecore

眉间皱痕 提交于 2019-12-06 10:01:39

问题


I have a component that needs to know how many components thats currently added to the very same placeholder, this since it needs to update a value of an html-attribute based on its index within the placeholder.

Is there anyway to get either the number of components thats already added to a placeholder, or to get the current-renderers index?

Usually I would just use a simple for-loop and set the attribute, but since its a placeholder with components thats not an option.

Thanks in advance!


回答1:


Try this:

var placeholder = "my-placeholder";
var renderingReferences = Sitecore.Context.Item.Visualization.GetRenderings(Sitecore.Context.Device, true);
var renderingsInPlaceholder = renderingReferences.Where(r => r.Placeholder.EndsWith('/' + placeholder, StringComparison.OrdinalIgnoreCase));
var numberOfRenderingsInPlaceholder = renderingsInPlaceholder.Count();

Update: Changed search for placeholder key from IndexOf to EndsWith.




回答2:


What is the HTML attribute you are trying to update and how are you planning on update this value? From C# code at render time? Or do you want to store this value when a component is added in the Page Editor and store the value against a Sitecore Item?

It depends on what your use-case is, but by suggestion for front-end use would be to execute this logic using JavaScript, otherwise you have to hook into Sitecore pipelines, find your HTML element and the add the attribute appropriately. Saving this value when a component is added means you need to r-run the login for the entire placeholder and update any stored values, since it will (should) be possible for the user to components anywhere...

Something like the following to add a order order data-attribute to a list of elements. If this is being used by another plugin the make sure you run this code before initializing your plugin.

// get element + its siblings
var $els = $('.selector').siblings().addBack();

// loop and add data-attr with index number
$els.each(function(index, element) {
    $(this).attr('data-sortorder', index);
}


来源:https://stackoverflow.com/questions/27357167/get-number-of-components-in-placeholder-sitecore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!