While reading this blog article about RSS templating, I came across the following twig code

if craft.app.request.segments|last == _self

I understand that the above command, in general, yields URL components as an array. But I don't understand under what scenario is the above condition true. What does _self mean in this context?


In Twig 2, _self seems to reference the name of the current template file.

Running {{ dump(_self) }} from the file /templates/test/index.twig would return the string test/index.

So what it's being used for in this example...

{% if craft.app.request.segments|last == _self %}

... is to test wether the last segment in the URL matches the template file. Or "is this template being loaded directly from the file-based routing or is it being included from another template?"

I would point out tho, this only matches the last segment. It assumes your feed.rss file it in the root templates directory. A more flexible approach would be to math the entire URI path.

{% if craft.app.request.pathInfo == _self %}

Later _self is used to generate a link with {{ url(_self) }}. This is the same as {{ url('feed.rss') }} but would update if you changed the file name (e.g. news.rss).

The whole point of that conditional is to replace the {% include 'feed.rss' %} with a <link rel="alternate" type="application/rss+xml" href="{{ url('feed.rss') }}">. Which seems a little complicated. After all, it provoked this Stack Exchange question. ;)

  • Thanks a lot for your explanation. everything is clear now :)
    – hvs
    Sep 10 '19 at 18:58

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.