kundefine
4 months ago

Laravel: Dynamically add and remove CSS or Script

Posted 4 months ago by kundefine

It is really easy to include all the common CSS or Script in the page. But the problem arise when you don't need some CSS or Script in the page. If you checkout my below code you will find out what i am trying to say.

I already instantiate my CSS class in header.blade.php and its included in the master.blade.php. After that index.blade.php extends master.blade.php

But the problem is When index.blade.php render it's create a new instance of the CSS class. header instance is gone.

I am trying to use my CSS Class

=> as service provider

=> share as view variable

=> as a Facade

  1. CSS.php (myclass for add or remove css)
namespace App\AppGlobal;

class CSS {
    public $css = []; // all my css filename and path is store in here

    // add css
    public function add($path, $filename) {
        $path = asset($path);
        $this->css[$filename] = $path;

        return $this->css;
    }


    // remove css
    public function remove($filename) {
        if(array_key_exists($filename, $this->css)) {
            unset($this->css[$filename]);
        }
    }

    // print css
    public function print() {
        $output = '';
        if(count($this->css)) {
            foreach($this->css as $filename => $path) {
                $output .= "<link rel='stylesheet' href='{$path}/{$filename}'>\n";
            }
        }
        echo $output;
    }
}

  1. master.blade.php (look like below)
{{-- include tha header --}}
@include('dashboard.inc.header')

{{-- the main content section --}}
@yield('main-content-section')

{{-- include tha footer --}}
@include('dashboard.inc.footer')
  1. header.blade.php (look like below)
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{config('app.name', 'ColorSpray')}}</title>

    {{-- add all common css --}}
    <?php $css->add('some/path', 'filename.css') ?>
    {{-- add additional css--}}
    @stack('add-css')
    {{-- remove exitsing css--}}
    @stack('remove-css')
    {{-- print all my css --}}
    <?php $css->print(); ?>
</head>
<body>
  1. index.blade.php (index.blade.php extends master.blade.php)
@extends('dashboard.layouts.master')

@push('add-css')
    {{-- add any additional css for index page --}}
    <?php
        $css->add('your/path/name', 'filename.css');
    ?>

@endpush

@push('remove-css')
    {{-- remove any common css that i don't need in index page --}}
    <?php
        $css->remove('your/path/name', 'commonFilename.css');
    ?>
@endpush


@section('main-content-section')

@endsection


@section('script')
@endsection

Please sign in or create an account to participate in this conversation.