官术网_书友最值得收藏!

The Controller

Now that we have found out more or less where we have to place our Controller, let's begin by creating a Controller folder inside our module's /src folder. Although not mandatory, this is a standard practice for Controller placement. Inside this folder, we can have our first Controller class file, that is, HelloWorldController.php.

Inside the file, we again have something simple (after the opening PHP tags):

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
* Controller for the salutation message.
*/
class HelloWorldController extends ControllerBase {

/**
* Hello World.
*
* @return string
*/
public function helloWorld() {
return [
'#markup' => $this->t('Hello World')
];
}

}

As expected, we start with the namespace declaration. If you read the preceding section, the namespace choice will make sense. Then, we have our Controller class that extends the Drupal 8 ControllerBase, which happens to provide some helper tools (such as the StringTranslationTrait, which I will explain later in the book). If you remember our route definition, we have a helloWorld method that returns an array.

If you've worked with previous versions of Drupal, this array (called a render array) will be familiar. Otherwise, what you need to know right now is that we are returning simple markup with the Hello World text wrapped in the translation service I hinted at in the previous paragraph. After the Controller returns this array, there will be an EventSubscriber that takes this array, runs it through the Drupal theme layer, and returns the HTML page as a response. The actual content returned in the Controller will be wrapped in the Main page content block that is usually placed in the main content region.

Now, our simple Controller is done. If we now clear the cache, we can go to /hello where we should encounter a new page that outputs the Our first route title and the Hello World content. Success!:

主站蜘蛛池模板: 大悟县| 奉新县| 武功县| 北票市| 辽中县| 汝州市| 金昌市| 莒南县| 伊宁市| 姚安县| 南通市| 都匀市| 栾川县| 衢州市| 沐川县| 汶上县| 会宁县| 资中县| 轮台县| 江孜县| 梧州市| 科尔| 东方市| 左贡县| 漳州市| 礼泉县| 高安市| 澄城县| 墨竹工卡县| 元谋县| 宣威市| 盐亭县| 洛宁县| 鱼台县| 平利县| 南乐县| 汝阳县| 镇平县| 义乌市| 杭锦后旗| 天峨县|