Get the current segment in a razor view

,

The following is not using Umbraco Engage; it uses the out-of-the-box segment services available in v16 and v17.

I’ve implemented my own ISegmentService. I also have an IContentFinder implementation. The content finder is setting the request.SetSegment(...) before the request.SetPublishedContent call. Using the standard @Model.MyProperty I get the correct content for the chosen segment, all working as expected behind the scenes and displaying the correct content.

However, there are times I would like to change the logic in the view based on the current segment Does anyone know how I can get the alias of the current segment in the razor view? I feel like I must be missing something obvious

Hi Matt,

I believe Kenn is doing just that in this article, so perhaps it could work for you?

https://kjac.dev/posts/tailoring-member-content-with-segments/

1 Like

Thanks Jacob, I’ll re-read that and see what I’ve missed!

Thanks Jacob, and @kjac, you’re both stars

I am injecting the segment using request.Segment(…) in a content finder and in Ken’s blog post he is injecting the segment using the VariationContextAccessor in middleware.

And then it clicked, I could consume the VariationContextAccessor in my Razor view. A quick test and I have my segment alias…

@inject IVariationContextAccessor VariationContextAccessor

var segmentAlias = VariationContextAccessor.VariationContext?.Segment;

Thanks so much!

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.