在Drupal 8的树枝中未传递变量值

时间:2018-10-12 06:22:22

标签: php twig drupal-modules drupal-8 drupal-blocks

我正在学习drupal 8,并以编程方式制作自定义块,并且还使用了树枝。我将两个变量传递给细枝,但问题是第二个变量的页面上只显示了第一个变量的值。而且,如果我更改第一个变量的变量名,该变量名也会从网页上消失。如何解决这个问题?

我的块构建功能代码

  public function build() {
  $role = "";
  $username = "";
  $userId = 0;
 $db = Database::getConnection();
 $query = $db->select('user__roles', 'x')
->fields('x', array('roles_target_id','entity_id'))
->condition('x.roles_target_id', 'administrator', '=');
 $data = $query->execute();

// Get all the results
$results = $data->fetchAll(\PDO::FETCH_OBJ);

// Iterate results
 foreach ($results as $row) {
$role = $row->roles_target_id;
$userId = $row->entity_id;
 }
 $query2 = $db->select('users_field_data','u')
    ->fields('u',array('name'))
    ->condition('u.uid',$userId,'=');
    $data2 = $query2->execute();

    // Get all the results
    $results2 = $data2->fetchAll(\PDO::FETCH_OBJ);

    foreach($results2 as $r)
    {
        $username = $r->name;
    }
return array(
  '#title' => $username,
  '#descriptions' => 'Websolutions Agency is the industry leading Drupal development agency in Croatia', 
);
 }  

我的树枝代码

 <h1> name: {{ title }} </h1>
<h2>{{ descriptions }}</h2>

我的.module文件的代码

 <?php
 /**
* Implements hook_theme().
*/
 function test_custom_theme() {
   return array(
     'test_custom_block' => array(
        'variables' => array('title' => NULL, 'descriptions' => NULL),
        'template' => 'block--test-custom',
    ),
);
}

3 个答案:

答案 0 :(得分:0)

我已将#theme和模板的名称更改为以模块名称开头。请找到以下示例。

src/Plugin/Block/[yourblockname].php

  public function build() {
    return [
      '#theme' => 'custom_blocks__front_apps',
      '#app' => 'your value',
    ];
  }

custom_blocks.module:

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'custom_blocks__front_apps' => [
      'variables' => [
        'app' => null
      ],
    ]
  ];
}

templates / custom-blocks--front-apps.html.twig

<p>Hello: {{ app }}</p>
<p>Base Label: {{ label }}</p>

答案 1 :(得分:0)

在您的block.php中,您应该添加正在使用的主题。这在模块文件中定义。 因此,您的return数组应如下所示:

    return array(
      '#theme' => 'test_custom_block'
      '#title' => $username,
      '#descriptions' => 'Websolutions Agency is the industry leading Drupal 
      development agency in Croatia', 
     );

因为在模块文件中您是这样说的

'test_custom_block' => array(...)

答案 2 :(得分:0)

检查一下以创建主题并使用树枝中的变量

File location - module/custom/MODULENAME/MODULENAME.module
    /**
     * @file
     * Twig template for render content
     */
    function MODULENAME_theme($existing, $type, $theme, $path) {
      return [
        'theme_name_template' => [
          'variables' => ['flag' => NULL],
        ],
      ];
    }
    To Use theme function use below code 
    return ['#theme' => 'theme_name_template', '#flag' => 1];