- Drupal 8 Module Development
- Daniel Sipos
- 225字
- 2021-07-02 12:22:41
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);
推薦閱讀
- Java程序設計(慕課版)
- 自制編譯器
- Cassandra Data Modeling and Analysis
- 嚴密系統設計:方法、趨勢與挑戰
- 組態軟件技術與應用
- PySpark Cookbook
- 智能手機APP UI設計與應用任務教程
- 持續集成與持續交付實戰:用Jenkins、Travis CI和CircleCI構建和發布大規模高質量軟件
- R語言:邁向大數據之路(加強版)
- HTML5移動前端開發基礎與實戰(微課版)
- 實驗編程:PsychoPy從入門到精通
- LabVIEW入門與實戰開發100例(第4版)
- 絕密原型檔案:看看專業產品經理的原型是什么樣
- Swift 2 Design Patterns
- Swift iOS Programming for Kids