How to target last active category in the shop URL?

TradingboTradingbo Member Posts: 24

Hi Support,

I'm working on a way to display sub category links within their parent cats on the collections page.

Im using:

{% if category.url is active %}

However this also targets the parents of a category as that URL is also active in the Domain URL when user is within a sub-category

Is their a way to target only the last active category in the shop URL?

E.g. URL = /showroom/indian-furniture/furniture-type/ only want to target /furniture-type/

{% if category.url is last.active %}

Best Answer

  • MilesbdMilesbd Posts: 20 moderator
    Accepted Answer

    Hi!

    Great Question!

    The most straightforward way to target the end of this type of string would be using the the "trim", "split" and "last" twig filters/functions to create an array out of the string, and target the last item in the array.

    With this method, you would have to be cautious and know the expected string, to know what to split on. In your case, with a URL it is fairly straightforward as you will be splitting on the "/".

    The trim function comes into play when the string ends on the character used to split: For example, if you're using your string "/showroom/indian-furniture/furniture-type/" and splitting on "/", the last item in an array would be blank. This is due to the last split being performed at the end of "furniture-type/" on the "/".

    The code that could be used by this would resemble:

    {% set categoryURL = "/showroom/indian-furniture/furniture-type/" | trim('/') |split('/') %}

     {{ categoryURL |last }}


    In the first line, you're taking your string, trimming the trailing "/", and then constructing the array "categoryURL" splitting on the "/" character.

    The second line in this example is outputting the last element of the "categoryURL" array - in this case "furniture-type"


    @gregarican You're completely right that javascript could also be used to evaluate the URL and parse the string.

    This would be in a similar format to the twig lines:

    var url = location.href.substring(0,location.href.length-1).split('/');

    url[url.length-1]

    On the first line, you would grab the URL "location.href", remove the trailing "/", and then create an array using the split function. You would then be able to specify the last item in the array by querying the length of the array, and subtracting 1 (second line of javascript)

    The difference between both methods lies in when you want the operation to be performed. Javascript will execute at the location it is placed (post page render) while the operation in twig will execute during page render.

Answers

Sign In or Register to comment.