Search code examples
orchardcmstaxonomy

Get url of a taxonomy field inside an alternate shape cshtml file in Orchard


I use Orchard 1.10.1. I have a CustomContentType that has a "Group" Taxonomy field . In Content-CustomContentType.Detail.cshtml alternate, I want to have a link to a certain taxonomy term. this is my code:

<a href='???'>@Model.ContentItem.CustomContentType.Group.Terms[0].Name</a>

How can I get the url to replace this '???' in above code.

Thanks in advance.


Solution

  • You have a few options available to you. I've just typed them all straight into the browser and Orchard is a tricky beast to navigate its model so if they blow up in your face let me know and I'll dig a bit deeper :)

    Let orchard make the entire link

    Looking at the TaxonomyItemLink.cshtml file you can see that you can display the link like this:

    @using Orchard.Taxonomies.Models
    @{
        TermPart part = Model.ContentPart;
    }
    @Html.ItemDisplayLink(part)
    

    So in your case you could use:

    @Html.ItemDisplayLink((ContentPart)Model.ContentItem.CustomContentType.Group.Terms[0])
    

    Just get the URL

    You can use @Url.ItemDisplayUrl() to turn a routable content item into a url.

    <a href="@Url.ItemDisplayUrl((ContentPart)Model.ContentItem.CustomContentType.Group.Terms[0])">
      @Model.ContentItem.CustomContentType.Group.Terms[0].Name
    </a>
    

    Because it's an extension method you can't pass a dynamic so you will need to cast the type. This is why the (ContentPart) is there.

    Just get the Slug

    Actually, in this case the TermsPart class already has a .Slug property on it, so this might also work:

    <a href="@Model.ContentItem.CustomContentType.Group.Terms[0].Slug">
      @Model.ContentItem.CustomContentType.Group.Terms[0].Name
    </a>
    

    I'm not sure if the slug just contains the end bit or its full url though.