Links

In Chapter 2, Creating Your First Module, we briefly looked at how we can work with links programmatically and how to build and render them in two different ways. We also noted that it's better to use the #link render element (and we now understand what this is) if we want the link to be alterable somewhere down the line. Now, let's take a look at how we can build a list of links using the helpful links theme hook.

The links theme hook takes an array of links to be rendered, optional attributes, an optional heading, and a flag to set the active class dynamically. It then uses the links.html.twig template to construct a <ul>, much like the item_list hook.

The most important variable here is the array of links, as it needs to contain individual arrays with the following keys: title (the link text), url (a Url object), and attributes (an array of attributes to add to each link item). If you look inside the template_preprocess_links preprocessor, you'll see that it takes each of these items and transforms them into a render array with the #type => 'link' (the render element).

In addition to the array of links, we can also pass a heading (just like with item_list) and a flag for setting the active class—set_active_class. The latter will make it add an is-active class onto the <li> item in the list and the link itself if the link matches the current route. Handy stuff, isn't it? However, for more information, check out the documentation above the template_preprocess_links() implementation. Now, let's see a quick example of using this in practice:

$links = [
[
'title' => 'Link 1',
'url' => Url::fromRoute('<front>'),
],
[
'title' => 'Link 1',
'url' => Url::fromRoute('hello_world.hello'),
]
];

return [
'#theme' => 'links',
'#links' => $links,
'#set_active_class' => true,
];

That is all. We build an array of link data and then construct the render array using the links theme hook. We also use the set_active_class option just for kicks. This means that the is-active class will be present on the first link if this is rendered on the home page or on the second link if rendered on the Hello World page. As simple as that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset