I want to create a Block-Module for drupal 8 (beta 12). To display the Content I want to use a twig-template (mytest-block.html.twig).
But the Twig-Template needs some Data to Display, So I need a Method to assign Some Variables from MytestBlock.php to the Template.
I know how to assign Variables from mytest.module, but I have no idea how to assign Variables from the Block-Plugin MytestBlock.php.
Or is it possible to access the instance of MytestBlock.php and therefore call a method which would return the variables as an array?
My MWE-Module consists of following files:
mytest/
├── mytest.info.yml
├── mytest.module
├── src
│ └── Plugin
│ └── Block
│ └── MytestBlock.php
└── templates
└── mytest-block.html.twig
File Content mytest.info.yml:
name: mytest
description: A Testmodule
core: 8.x
package: Custom
version: 0.1
dependencies:
- block
type: module
File Content mytest.module:
<?php
function mytest_theme() {
return array('mytest_block' =>
array('variables' => array('test' => 'hello')));
}
function template_preprocess_mytest_block(&$variables) {
$variables["test2"] = "hello2";
//a call to get_variables() would also be an option, e.g.:
//$variables = array_merge($variables, $A_INSTANCE->get_variables());
}
File Content mytest-block.html.twig:
Template
{{ test }}
{{ test2 }}
{{ test3 }}
{{ test4 }}
File Content MytestBlock.php:
<?php
namespace Drupal\mytest\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
/**
* Provides a Test-Block
*
* @Block(
* id = "MytestBlock",
* admin_label = @Translation("My Testblock"),
* )
*/
class MytestBlock extends BlockBasMytestBlock.phpe implements BlockPluginInterface {
public function build() {
return array(
'#theme' => 'mytest_block',
/*here I want to assign some variables: e.g.:
* test3 = hello3 */
);
}
public function get_variables() {
retrun array("test4" => "hello4");
}
}
In this example, only test and test2 are assigned, but I want, that test3 and test4 are assigned too.