I have a list of items which I want to output in a razor view. Between each item I want to add a separator line, like this:
item1 | item2 | item3
The simplest way to loop through items is with a foreach:
@foreach(var item in Model.items){
<span>@item.Name</span> |
}
Unfortunately this adds an extra separator line at the end of the list. Is there a simple way to skip this last separator line?
Not sure if this is the simplest way, or if these is a more elegant way, but you could do something like;
So you are basically checking to see if the
item
is the last item in the list.Not tried this code sample, so you might need to tweek it.
Keep a counter variable and inside the loop and check whether it is the last item or not.
and the short version is
Combining the other answers here with this article on inline templates, I came up with this helper method, which can be put in an extension class:
The way to use it would then be
This supports html in both the items and the separator.
You can use
string.Join
:Using
string.Join
negates the need to check for the last item.You can mix this with a Razor
@helper
method for more complex markup:You could even create a helper method to abstract the
Html.Raw()
andstring.Join()
calls:Usage: