Attaching a library
In many cases, we may be developing some CSS or JS functionality that is specific
to an individual page. When we are presented with this requirement, we have the
ability to attach a library to a page using two different methods.Using Twig to attach a library
While we will be learning all about Twig a little later in the chapter, we need to pause for a moment to reference a Twig function named {{ attach_library() }}. This function allows us to add to any Twig template a library that may include CSS or JS that will load on that page only.For example, if we wanted to add the Slick Carousel () to our page, we may define the library within our example.libraries.yml file as follows:
# Slick
slick:
version: VERSION
css:
theme:
vendor/slick/slick.css: {}
js:
vendor/slick/slick.min.js: {}
dependencies:
- core/jquery
We could then turn around and add the following to our Twig template:
{{ attach_library('example/slick') }}
This provides us with some nice functionality to define individual libraries for various user functions and also to have those assets used wherever we choose to attach them.
Using the preprocess functions to attach a library
Another method to attach a library to an individual page depends on creating a *.theme file, which allows us to use preprocess functions to manipulate page variables. We will learn a lot more about creating a *.theme file a little later in the chapter, but it's important to note that we could attach the same Slick Carousel to our homepage without globally calling it by using a preprocess function, as shown in the following example: function example_preprocess_page(&$variables) {
if ($variables['is_front']) {
$variables['#attached']['library'][] = 'example/slick';
}
}
Here, we are checking to see whether we are on the homepage of our website and attaching our Slick library using the #attached library array. Again, this may seem a little bit advanced at this point but does merit mentioning. The last section we will want to cover when working with any *.info.yml file is about regions that can be defined for the layout of our theme.
Above Two you can add libraries in the theme we hope this block will help you to how to attached libraries in theme
No comments:
Post a Comment