EPiServer 7 LinkItemCollection extension
I found it useful to have an extension method for the linkitemcollection, as it is often used in UL/LI lists.
This is for EPiServer CMS 7. It handles both EPi pages and external links.
This is for EPiServer CMS 7. It handles both EPi pages and external links.
C#:
public static string GetItemsList(this LinkItemCollection links)
{
return GetItemsList(links, false);
}
/// <summary>
/// Returns a LI a href listing, with option for class "last" on the last li element
/// </summary>
/// <param name="links"></param>
/// <returns></returns>
public static string GetItemsList(this LinkItemCollection links, bool addClassLast)
{
StringBuilder sb = new StringBuilder("");
if (links == null || links.Count < 1)
return "";
int total = links.Count;
int counter = 1;
foreach (LinkItem linkItem in links)
{
UrlBuilder url = new UrlBuilder(linkItem.Href);
bool isEPiServerPage = PermanentLinkMapStore.ToMapped(url);
if (isEPiServerPage && PermanentLinkUtility.IsMappableUrl(url))
{
PageData page = DataFactory.Instance.GetPage(PageReference.Parse(url.QueryId));
if (page != null && !page.IsDeleted && page.CheckPublishedStatus(PagePublishedStatus.Published))
{
sb.Append(string.Format(GetPattern(addClassLast, counter, total), page.PageName, page.PageLink.GetFriendlyURL(), linkItem.Target));
}
}
else if (linkItem.Href.StartsWith("http"))
{
sb.Append(string.Format(GetPattern(addClassLast, counter, total), linkItem.Text, linkItem.Href, linkItem.Target));
}
counter++;
}
return sb.ToString();
}
static string GetPattern(bool addClassLast, int counter, int total)
{
if (addClassLast && counter == total)
return "<li class=\"last\"><a href=\"{1}\" target=\"{2}\">{0}</a></li>";
return "<li><a href=\"{1}\" target=\"{2}\">{0}</a></li>";
}
Inga kommentarer:
Skicka en kommentar