Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Call stylesheet only at a particular page in Drupal 8

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 356
    Comment on it

    In Drupal 8, if we are required to add some Stylesheets or JavaScripts in a particular page then to achieve the goal we need THEME.info.yml and THEME.libraries.yml file of our theme.

     

    Lets see how can we achieve it.

     

    In the .info.yml file we defined the global library that contains global styles.
    Now in the .libraries.yml file we initialize our specific library.

     

    Let's define them in the following code :

     

    THEME.info.yml

     

    name: Basic
    description: My theme.
    type: theme
    core: 8.x
    
    # Regions
    regions:
      header: Header
      content: Content
      footer: Footer
    
    # Scripts & Styles
    libraries:
      - basic/global

     

    THEME.libraries.yml

     

    global:
      css:
        theme:
          css/style.css: {}
        css/print.css: { media: print }
      js:
        js/scripts.js: {}
    
    myslider:
      css:
        theme:
          css/myslider.css: {}
      js:
        js/myslider.js: {}
      dependencies:
        - core/jquery

     

    In the above codes we have defined two files .info.yml and .libraries.yml files.
    Lest, if we need to apply custom css myslider.css and script myscript.js in myslider page only.

    For that we have to defined the css and js in .libraries,yml under the name mysider.

    Now, the thing is we have to call the library myslider at our myslider page for that we will use our twig tag to attach this library.


    in your myslider.html.twig page add the below line.

     

    {{ attach_library('MYTHEME/myslider') }}

    Now our library will get added to the only template page in which we need to call.

    In this way we apply our styling to only those template file where they are required. It does helps in fast rendering of page as browser doesn't need to load unnecessary file.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: