How to get current path for user profile field?

On the user profile page, I want to add link field which will link to a view page.

For example, if the current path is:

sitename/user/1 (profile page of user-1)

The link should be:


It should take the user-id from the current-path. It should redirect to sitename/user/1/view-page, in general sitename/user/%/view-page, which is my contextual view path.

How can build this link field for the profile page?


One way to go about this is a theme override of the user profile page:

  • Copy over core/modules/user/templates/user.html.twig over to your theme's template directory.
  • Have your theme implement template_preprocess_user() in your MYTHEME.theme file to inject a custom URL variable.
  • Modify your theme's user.html.twig to contain the HTML for the link.

For example, in your MYTHEME.theme:

use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Drupal\Core\Url;

 * Implements hook_preprocess_user() for user.html.twig.
function MYTHEME_preprocess_user(&$variables) {
  if (\Drupal::request()->get(RouteObjectInterface::ROUTE_NAME) == 'entity.user.canonical') {
    $variables['view_page_path'] = Url::fromUri('base:' . \Drupal::service('path.current')->getPath())->toString() . '/view-page';

In your user.html.twig:

{% if view_page_path %}
  <a href="{{ view_page_path }}">MY VIEW PAGE</a>
{% endif %}

Category: 8 Time: 2016-07-31 Views: 0
Tags: links

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.139 (s). 12 q(s)