Simple login link module on Drupal 9

Today we will make a small module for displaying in the Drupal site template 9 links to user registration / login if the user is not logged in and a link to the user account if the user is logged in.

We create a custom folder in the modules folder, inside we create the folder of our module, in our example it will be the dartharth_users folder, inside which we create the src, template folders and the dartharth_users.info.yml and dartharth_users.module files.

Inside the dartharth_users.module file add the following

<?php
/**
 * @file
 */
function dartharth_users_theme() {
    $info['users'] = [
        'variables' => [
            'current_user' => '',
        ],
    ];
    return $info;
}

Inside the dartharth_users.info.yml file add the following

name: User login
description: 'Simple user links'
type: module
core_version_requirement: ^8 || ^9
version: 1.0
package: DarthArth
dependencies:
  - block

Inside the src folder, create a Plugin folder, and inside it, a Block folder with a Users.php file with the following content

<?php

/**
 * @file
 * Contains \Drupal\dartharth_users\Plugin\Block\Users.
 */

namespace Drupal\dartharth_users\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountProxyInterface;
    use Drupal\user\Entity;

/**
 * @Block(
 *   id = "dartharth_users",
 *   admin_label = @Translation("Users Block"),
 *   category = @Translation("DarthArth")
 * )
 */
class Users extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function build() {
        $current_user = [];
        $uid = \Drupal::currentUser()->id();
        $user = \Drupal\user\Entity\User::load($uid);
        $name = $user->get('name')->value;
        $uid= $user->get('uid')->value;
        $current_user[] = [
            'url' => '/user/'.$uid.'',
            'name' => $name,
        ];
        $block = [
            '#theme' => 'users',
            '#current_user' => $current_user,
            '#cache' => [
                'max-age' => 0,
            ]
        ];
        return $block;
    }
}

Inside the tepmlates folder, create a file users.html.twig with the following content

<div id="login_link">
    {% if logged_in %}
        {% for item in current_user %}
            <a href="{{ item.url }}" >{{ item.name }}</a>
        {% endfor %}
    {% else %}
        <a href="/user/register" >Register</a> or <a href="/user/login" >Login</a>
    {% endif %}
</div>

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.