質問

Am new to Drupal so this is a very fundemental question.

How do I display the current username ? In a custom Block? I beleive is the $user->name session variable.

Do I create a Custom Block Type? If so how do I reference the username?

Do I edit files on the file system? If so which files?

Do I create new files? If so where?

In other web frameworks the templating engine allows server script tags... ex.. like

<%= username %>

Ive tried putting

$user->name and {{app.user}}

into the custom block editor but nope, I've learned it's a WYSISYG with no way to render

All I want to do is display a user name in a block I can add a label too.

Any help appriciated.

役に立ちましたか?

解決

You can do this in sevaral ways, one of this could be use a preprocess function. In your custom module in the .module file or your custom theme in the .theme file (recommended) write this:

/**
 * Implements hook_preprocess_HOOK().
 */
function [my_module_or_theme]_preprocess_block(&$variables) {
  $variables['username'] = \Drupal::currentUser()->getUsername();
} 

and then in your template suggestions of block.twig.html print the variable {{ username }}

他のヒント

To answer my question I created a custom module with a block.

That needed a folder for the module, a .info.yml file and a file for the block.

1) A folder for the module modules/custom/my_show_user

2) The file modules/custom/my_show_user/my_show_user.info.yml

name: Show User Module
description: Displays the logged in user name in a block.
package: Custom

type: module
core: 8.x

dependencies:
  - drupal:block

php: 5.6

3) The file modules/custom/my_show_user/src/Plugin/Block/UserNameBlock.php

<?php

namespace Drupal\my_show_user\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'User Name' Block.
 *
 * @Block(
 *   id = "my_show_user",
 *   admin_label = @Translation("Show User"),
 *   category = @Translation("Show User"),
 * )
 */

class UserNameBlock extends BlockBase {

    /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t(\Drupal::currentUser()->getUsername()),
    );
  }

}

That's it done. .

fyi, any time a change is made clear the cache to see it
Manage>Configuration>Performance>Clear All Caches

In Structure > Place Block a block called UserNameBlock can now be selected and it displays the current logged in user.

Adding the dependency - drupal:block and keeping the commented annotations @Block and @inheritdoc was key.

the line

'#markup' => $this->t('any html string can go here ' . \Drupal::currentUser()->getUsername() . ' concatenated with data in the template, in this case username' ),

is the entry point for your 'custom template'.

public function build() { return [ '#markup' => $this->t(\Drupal::currentUser()->getUsername()), ]; }

ライセンス: CC-BY-SA帰属
所属していません drupal.stackexchange
scroll top