- Drupal 8 Module Development
- Daniel Sipos
- 218字
- 2021-07-02 15:45:18
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);
推薦閱讀
- iOS面試一戰(zhàn)到底
- Spring Boot開發(fā)與測試實戰(zhàn)
- Maven Build Customization
- 深入淺出Windows API程序設計:編程基礎篇
- Mastering PHP Design Patterns
- Big Data Analytics
- Drupal 8 Configuration Management
- HTML5+CSS3網(wǎng)頁設計
- Ext JS 4 Web Application Development Cookbook
- H5頁面設計:Mugeda版(微課版)
- Android項目實戰(zhàn):手機安全衛(wèi)士開發(fā)案例解析
- App Inventor創(chuàng)意趣味編程進階
- Docker:容器與容器云(第2版)
- HTML5程序開發(fā)范例寶典
- IBM DB2 9.7 Advanced Application Developer Cookbook