Having access to a site’s URL in your templates can come in handy for many different use cases, such as determining if your on the admin/people page as apposed to admin/reports/dblog or admin/content. These three pages might seem to bear on common relationship, however there is at least one. Users.
I edited the user in the admin/people page so rather than showing just username, know shows:
- Firstname
- Lastname
- Username
However, in making this change I discovered that when on admin/content or admin/reports/dblog pages it would also so all the details. So I needed to add an if statement to catch which page I was on. Subsequently, you can get the current URL and parse it for a substring like this:
{% set site_url = url("<current>") %} {% if 'people' in site_url['#markup']|render|render %} <div class="tw-pt-2"> <div class="tw-inline-block tw-w-52 tw-text-gray-400">{{ name }}</div> <div class="tw-inline-block tw-pl-10 tw-text-gray-500">{{ mail }}</div> </div> {% endif %}
Note, this doesn't show the full example of how to change the details, I wanted to focus on determining the people.
Other options
Absolute URL to the front page:
<a href="{{ url('<front>') }}">{{ 'Home'|t }}</a>
An absolute URL to a specific node:
<a href="{{ url('entity.node.canonical', { 'node': 123 }) }}">{{ 'Visit node 123'|t }}</a>
What about if you are working in a node template and have a node variable available, you can generate an absolute URL to the current node:
<a href="{{ url('entity.node.canonical', { 'node': node.id() }) }}">{{ 'Visit this page'|t }}</a>
Extra notes
If you are using url('<front>'), note this is an array. I was using the 'front' is the following way
{% set frontUrl = url('<front>') %} {% set path = 'related-projects' %} {% set hrefPathTag = 'f[0]'|url_encode ~ '=' ~ 'tags:'|url_encode %} {% for tag in items|slice(startPos, length) %} {% set tag = drupal_field('name', 'taxonomy_term', tag.content['#options'].entity.tid.value) %} {% set tagTitle = tag|render|striptags|trim %} {% set href = '?' ~ hrefPathTag ~ tagTitle|url_encode %} <a href="{{ frontUrl|render ~ path ~ href }}" alt="{{ tagTitle|title }}" class="tw-no-underline"> <div class="dark-blue-tag">{{ tagTitle|title }}</div> </a> {% endfor %}
So the 'front' path renders correctly, add |render
frontUrl|render