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

The link

Now that we have a Url object, we can use it to generate a link. We can do this in two ways:

  • Use the LinkGenerator service (named link_generator) and call its generate() method passing the link text and the Url object we have obtained. This will return a GeneratedLink object, which contains the actual string representation of the link, that is, the markup.
  • Use the Link class, which wraps a render element (we will talk more about render elements in the Theming chapter) to represent the link.

Let's take a look at an example of both, from start to finish.

Consider this example of generating a link using the service:

$url = Url::fromRoute('my_route', ['param_name' => $param_value]);
$link = \Drupal::service('link_generator')->generate('My link', $url);

We can then directly print $link because it implements the __toString() method.

Now, consider this example of generating a link using the Link class:

$url = Url::fromRoute('my_other_route');
$link = Link::fromTextAndUrl('My link', $url);

We now have $link as a Link object whose toRenderable() returns a render array of the #type => 'link'. Behind the scenes, at render time, it will also use the link generator to transform that into a link string.

If we have a Link object, we can also use the link generator ourselves to generate a link based on it:

$link = \Drupal::service('link_generator')->generateFromLink($linkObject);
主站蜘蛛池模板: 墨脱县| 泾阳县| 天全县| 北京市| 徐汇区| 靖安县| 江门市| 寿光市| 娄烦县| 从江县| 万年县| 盘锦市| 马公市| 岑溪市| 诸暨市| 萨嘎县| 秦皇岛市| 博湖县| 望谟县| 南丹县| 买车| 诸城市| 师宗县| 珲春市| 江安县| 尤溪县| 万山特区| 盐山县| 巴南区| 泗洪县| 正阳县| 辽阳市| 安庆市| 潮安县| 上思县| 安康市| 天津市| 洪洞县| 拜泉县| 五峰| 区。|