spatie/laravel-google-fonts

repository·main·Indexed 19 days ago

https://github.com/spatie/laravel-google-fonts

A Laravel package for self-hosting Google Fonts by automatically scraping, downloading, and inlining font assets to improve privacy and performance. It provides a @googlefonts Blade directive, a google-fonts:fetch Artisan command for prefetching assets, and configuration options for storage disks, CSS inlining, and CSP nonce support.

Tokens
2.4K
Snippets
11
Records
14
Agent score
66%

What's inside spatie/laravel-google-fonts

  1. Use the @googlefonts Blade directive

    main

    To load fonts in your application, register the Google Fonts embed URL in your configuration and use the @googlefonts Blade directive in your layout.

    By default, the package inlines the CSS to reduce network round-trips. You can load the default font by calling @googlefonts without arguments, or specify a specific key defined in your config.

    // config/google-fonts.php
    
    return [
        'fonts' => [
            'default' => 'https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,400;0,700;1,400;1,700&display=swap',
            'code' => 'https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,700;1,400&display=swap',
        ],
    ];
    {{-- resources/views/layouts/app.blade.php --}}
    
    <head>
        {{-- Loads Inter (the 'default' key) --}}
        @googlefonts
    
        {{-- Loads IBM Plex Mono (the 'code' key) --}}
        @googlefonts('code')
    </head>
  2. Configure google-fonts.php

    main

    The configuration file allows you to control how fonts are handled. Key options include:

    • fonts: An associative array of Google Fonts embed URLs.
    • disk: The filesystem disk used to store local font files (defaults to public).
    • path: The directory within the disk where fonts are stored (defaults to fonts).
    • inline: Whether to inline the CSS in the HTML (defaults to true).
    • preload: Whether to generate <link rel="preload"> meta tags (defaults to false).
    • fallback: Whether to fall back to Google's servers if local fetching fails (defaults to !env('APP_DEBUG')).
    • user_agent: The User Agent string used to request the stylesheet from Google. The default targets modern browsers supporting WOFF 2.0.
    return [
        'fonts' => [
            'default' => 'https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,400;0,700;1,400;1,700',
        ],
    
        'disk' => 'public',
    
        'path' => 'fonts',
    
        'inline' => true,
    
        'preload' => false,
        
        'fallback' => ! env('APP_DEBUG'),
    
        'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15',
    ];
  3. Handle legacy browser support for fonts

    main

    The package defaults to a User Agent that targets modern browsers supporting WOFF 2.0. If you need to support legacy browsers (like Internet Explorer) that do not support WOFF 2.0, you must specify a different user_agent string in your config/google-fonts.php.

    Note: Using a legacy user agent will make the font files heavier for all visitors, including modern browsers.

  4. Use @googlefonts with spatie/laravel-csp

    main

    If you use spatie/laravel-csp for Content Security Policy management, you can pass a nonce to the @googlefonts directive by passing an array of options.

    <head>
        {{-- Loads Inter with nonce --}}
        @googlefonts(['nonce' => csp_nonce()])
    
        {{-- Loads IBM Plex Mono with nonce --}}
        @googlefonts(['font' => 'code', 'nonce' => csp_nonce()])
    </head>
  5. Configure Google Fonts via config/google-fonts.php

    main

    The GoogleFonts singleton is initialized using settings from the google-fonts.php configuration file. You can customize the following keys:

    • disk: The Laravel filesystem disk used to store the downloaded fonts.
    • path: The directory path within the disk where fonts are stored.
    • inline: Whether to inline the font CSS directly into the HTML.
    • fallback: The fallback font to use.
    • user_agent: The User Agent string used when fetching fonts from Google.
    • fonts: An array of fonts to be managed.
    • preload: Whether to add preload attributes to the font links (defaults to false).
  6. Prefetch fonts using the artisan command

    main

    To ensure fonts are downloaded and ready before users visit your site, run the google-fonts:fetch command. This will scrape the CSS, fetch assets from Google, and store them locally based on your configuration.

    php artisan google-fonts:fetch
  7. Render Google Fonts using the Fonts class

    main

    The Spatie\GoogleFonts\Fonts class is used to generate the HTML required to embed your self-hosted Google Fonts. It implements Htmlable, meaning it can be rendered directly in Laravel Blade templates.

    Depending on how the object was instantiated, you can choose how to output the HTML:

    • toHtml(): The primary method for rendering. It automatically decides between an inline <style> block or a <link> tag based on the $preferInline property.
    • inline(): Returns an HTML <style> block containing the localized CSS.
    • link(): Returns an HTML <link> tag pointing to the localized CSS URL.
    • fallback(): Returns a fallback <link> tag pointing to the original Google Fonts URL if localized assets are unavailable.
    // In a Blade template
    {{ $fonts }}
    
    // Or explicitly calling toHtml()
    {!! $fonts->toHtml() !!}
  8. Load fonts using the GoogleFonts service

    main

    The load() method is the primary entry point for retrieving font assets. It attempts to load fonts from the local filesystem (self-hosted) if they have been previously downloaded. If they are not found locally, it fetches them from Google's servers and saves them to your local storage.

    Parameters

    • options (string|array): An array containing:
      • 'font' (string): The name of the font to load (must match a key in the configured fonts array).
      • 'nonce' (string|null): A Content Security Policy (CSP) nonce to be applied to the generated tags.
    • forceDownload (bool): If set to true, the service will bypass the local cache and re-download the fonts from Google immediately.

    Return Value

    Returns an instance of Fonts which contains the CSS and metadata required to render the fonts in your application.

    Error Handling

    • Throws a RuntimeException if the requested font name does not exist in the configuration.
    • If fallback is enabled in the configuration, the service will catch exceptions and return a Fonts instance pointing directly to the Google Fonts URL instead of failing.
    // Loading a font by name
    $fonts = $googleFonts->load('roboto');
    
    // Loading a font with a CSP nonce
    $fonts = $googleFonts->load([
        'font' => 'roboto',
        'nonce' => 'your-csp-nonce',
    ]);
    
    // Forcing a re-download of the assets
    $fonts = $googleFonts->load('roboto', true);