2

I need to output the relative URL for the current page for a GA event label. According to Craft 3 docs, it seems like rootRelativeUrl() as in:

{% relative = entry.rootRelativeUrl() %} 

should do the job but it generates and 'Calling unknown method' error. Any ideas?

2

The easy way:

{% set relativeUrl = craft.app.request.url %}

Otherwise, and as a general example of using Craft helper functions...

rootRelativeUrl is actually a method on the UrlHelper class, thus it's not available on elements I don't think.

Try this:

{# Use any Craft "helper" classes in your Twig templates by creating them #}
{% set urlHelper = create(
    "craft\\helpers\\UrlHelper"
) %}
{# You can then call any of their methods, e.g.: #}
{{ set relative = urlHelper.rootRelativeUrl(entry.url) }}

(or you could get the url from craft.request.url for example)

(snippet pinched from from https://nystudio107.com/blog/cutting-the-cord-removing-plugins)

2
  • Thanks! You put me on the right track. This worked: {% set relativeUrl = craft.app.request.url %} Apr 10 '20 at 16:22
  • Well LOL yes, that's the easier way. I got side tracked by the rootRelativeUrl thing. Also I think in Craft 2 the request url was the full, not relative url...but I might be mis remembering. Apr 10 '20 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.