I have a blog section on a Umbraco site, where I want to get all tags from each blog item and combine them in a list without dublicates, so that I can use the taglist as a filter.
I have this section where tags will be listed
<ul id="blogTags" class="inline-list">
<li class="tag-item"><a href="#">Tag 1</a></li>
<li class="tag-item"><a href="#">Tag 2</a></li>
<li class="tag-item"><a href="#">Tag 3</a></li>
<li class="tag-item"><a href="#">Tag 4</a></li>
</ul>
On my BlogItem doctype I have a field tagsList
where the editor can input a comma-separated list of tags.
So basically I want to get all tags from all BlogItems and combine them into a list where dublicates are removed.
I am getting all blog items using:
var blogItems = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "BlogItem" && x.IsVisible());
But I am not sure how to get all tags, combine and remove dublicates.
one way of doing it is create a Hashset to store tags and use foreach to add it.
so you can do something like:
HashSet<string> uniqueTagList = new HashSet<string>();
var blogItems = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "BlogItem" && x.IsVisible());
var tags = blogItems.Select(x => x.GetPropertyValue<string>("tagsList"));
foreach(var tag in tags)
{
var splitTag = tag.Split(',');
foreach(var singleTag in splitTag)
{
uniqueTagList.Add(singleTag);
}
}
then your uniqueTagList
is a list of all the tag, which you can use to create your list
<ul id="blogTags" class="inline-list">
@foreach(var tag in uniqueTagList)
{
<li class="tag-item"><a href="#">@tag</a></li>
}
</ul>
but beware that if you have a lot of children, this can take some time.
So I would suggest checkout Umbraco tag data type to do something like this:
https://shermandigital.com/blog/display-umbraco-tags-on-razor-templates/