Sitecore Box

Sitecore web developer at Americaneagle.com

Sitecore Box

Find the item's languages Programmatically in Sitecore




Everybody knows how to find the languages for any item in the Sitecore tree. This can be done by selecting the item and clicking on the language dropdown on the right side as you can see in the below screenshot.




During my work, I needed to find all items with their version languages so I created MVC view to show them as an HTML table.

@using Sitecore.Data.Items
@using System.Text;
@using Sitecore.Data.Fields;
<!DOCTYPE html>
<!--[if (lt IE 9) ]> <html lang="en" class="no-js oldie"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html>
<!--<![endif]-->
<head>
</head>
<body>
@{
HtmlString result = new HtmlString("");
StringBuilder stringBuilder = new StringBuilder();
string startItemPath = Sitecore.Context.Site.StartPath;
Item startItem = Sitecore.Context.Database.GetItem(startItemPath);
if (startItem != null)
{
result = new HtmlString(Render(startItem, stringBuilder));
}
}
<table>
<thead>
<tr>
<th>Item ID</th>
<th>Item name</th>
<th>Language</th>
</tr>
</thead>
<tbody>
@result
</tbody>
</table>
@functions
{
private bool HasLanguageVersion(Sitecore.Data.Items.Item item, string languageName)
{
var language = item.Languages.FirstOrDefault(l => l.Name == languageName);
if (language != null)
{
var languageSpecificItem = global::Sitecore.Context.Database.GetItem(item.ID, language);
if (languageSpecificItem != null && languageSpecificItem.Versions.Count > 0)
{
return true;
}
}
return false;
}
public bool HasPresentation(Item item)
{
try
{
LayoutField field = item.Fields[Sitecore.FieldIDs.LayoutField];
return field != null && !string.IsNullOrEmpty(field.Value);
}
catch (System.Exception ex)
{
return false;
}
}
public string Render(Item startItem, StringBuilder stringBuilder)
{
bool flag = false;
if (startItem.Children != null && startItem.Children.Count != 0)
{
foreach (Item child in startItem.Children)
{
flag = false;
if (child.Languages.Length > 1 && HasPresentation(child) && child.Languages.Any(x => x.Name == "en"))
{
foreach (var lang in child.Languages)
{
if (HasLanguageVersion(child, lang.Name))
{
flag = true;
stringBuilder.Append("<tr>");
stringBuilder.Append(" <td>");
stringBuilder.Append(child.ID);
stringBuilder.Append(" </td>");
stringBuilder.Append("<td>");
stringBuilder.Append(child.DisplayName);
stringBuilder.Append("</td>");
stringBuilder.Append("<td>");
stringBuilder.Append(lang.Name);
stringBuilder.Append("</td>");
stringBuilder.Append("</tr>");
}
}
if (child.HasChildren)
{
Render(child, stringBuilder);
}
}//foreach
}
}
return stringBuilder.ToString();
}
}
</body>
</html>
view raw languages hosted with ❤ by GitHub


0 comments:

Post a Comment