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

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 by 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 as well as some cache metadata.
  • Use the \Drupal\Core\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() method 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 its own data:

$link = \Drupal::service('link_generator')->generateFromLink($linkObject); 
主站蜘蛛池模板: 乐昌市| 正镶白旗| 乐业县| 龙海市| 开平市| 延川县| 英超| 大同市| 和龙市| 新巴尔虎右旗| 奉贤区| 永修县| 德惠市| 平乡县| 察雅县| 高要市| 公主岭市| 西贡区| 柳州市| 菏泽市| 咸阳市| 江口县| 浦东新区| 敦煌市| 繁峙县| 南木林县| 贵阳市| 阿瓦提县| 扶沟县| 无极县| 宁陵县| 阿鲁科尔沁旗| 大竹县| 北安市| 鄢陵县| 志丹县| 房产| 五河县| 荔波县| 金坛市| 盐城市|