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

Route variables

A very common requirement is to have a variable route parameter (or more) that gets used by the code that maps to the route, for example, the ID or path alias of the page you want to show. These parameters can be added by wrapping a certain path element into curly braces, like so:

path: '/hello/{param}'

Here, {param} will map to a $param variable that gets passed as an argument to the controller or handler responsible for this route. So, if the user goes to the hello/jack path, the $param variable will have the jack value and the controller can use that.

Additionally, Drupal 8 comes with parameter converters that transform the parameter into something more meaningful. For example, an entity can be autoloaded and passed to the Controller directly instead of an ID. Also, if no entity is found, the route acts as a 404, saving us a few good lines of code. To achieve this, we will also need to describe the parameter so that Drupal knows how to autoload it. We can do so by adding a route option for that parameter:

options:
parameters:
param:
type: entity:node

So, we have now mapped the {param} parameter to the node entity type. Hence, if the user goes to hello/1, the Node with the ID of 1 will be loaded (if it exists).

We can do one better. If, instead of {param},we name the parameter {node} (the machine name of the entity type), we can avoid having to write the parameters option in the route completely. Drupal will figure out that it is an entity and will try to load that node by itself. Neat, no?

So keep these things in mind the next time you need to write dynamic routes.

主站蜘蛛池模板: 丰原市| 那曲县| 泰宁县| 泽州县| 留坝县| 东乌珠穆沁旗| 滨州市| 宽城| 平阳县| 东莞市| 灵台县| 阿拉尔市| 南京市| 莆田市| 深圳市| 乌兰察布市| 阳山县| 简阳市| 兴海县| 专栏| 木里| 贵州省| 太仆寺旗| 海门市| 朝阳县| 河东区| 延寿县| 启东市| 巴林左旗| 轮台县| 龙陵县| 阜阳市| 满洲里市| 申扎县| 砀山县| 丁青县| 沛县| 子洲县| 柘荣县| 甘孜| 仁化县|