- 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);
推薦閱讀
- Mastering Entity Framework Core 2.0
- Deploying Node.js
- Advanced Machine Learning with Python
- Apache ZooKeeper Essentials
- 編程卓越之道(卷3):軟件工程化
- 無代碼編程:用云表搭建企業數字化管理平臺
- 實戰低代碼
- Data Analysis with Stata
- R的極客理想:工具篇
- 嚴密系統設計:方法、趨勢與挑戰
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Julia高性能科學計算(第2版)
- Raspberry Pi Home Automation with Arduino(Second Edition)
- MINECRAFT編程:使用Python語言玩轉我的世界
- 硬件產品設計與開發:從原型到交付