- 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);
推薦閱讀
- Reporting with Visual Studio and Crystal Reports
- 企業級Java EE架構設計精深實踐
- Photoshop智能手機APP UI設計之道
- Learning Salesforce Einstein
- 微服務從小白到專家:Spring Cloud和Kubernetes實戰
- 移動互聯網軟件開發實驗指導
- Raspberry Pi Robotic Blueprints
- Android嵌入式系統程序開發:基于Cortex-A8(第2版)
- ASP.NET求職寶典
- Scrapy網絡爬蟲實戰
- Robot Framework Test Automation
- SEO教程:搜索引擎優化入門與進階(第3版)
- C語言程序設計教程
- 零基礎學Java(第5版)
- 基于JavaScript的WebGIS開發