brieucthomas / elixir-twig-extension by Brieucthomas

Laravel Elixir twig extension
7,840
2
1
Package Data
Maintainer Username: Brieucthomas
Package Create Date: 2016-07-01
Package Last Update: 2016-12-06
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-12-15 15:16:39
Package Statistics
Total Downloads: 7,840
Monthly Downloads: 254
Daily Downloads: 4
Total Stars: 2
Total Watchers: 1
Total Forks: 8
Total Open Issues: 0

Laravel Elixir Twig Extension

Build Status

The Laravel Elixir version task appends a unique hash to filename, allowing for cache-busting.

elixir(function(mix) {
    mix.version("css/all.css");
});

For example, the generated file name will look something like: all-16d570a7.css.

In Laravel, you can use in your views the elixir() function to load the appropriately hashed asset:

<link rel="stylesheet" href="{{ elixir("css/all.css") }}">

This twig extension is an adaptation of this elixir() function.

Requirements

You need PHP >= 5.5.9 to use the library, but the latest stable version of PHP is recommended.

Install

Install using Composer:

composer require brieucthomas/elixir-twig-extension

This will edit (or create) your composer.json file and automatically choose the most recent version.

Documentation

Register the extension

use BrieucThomas\Twig\Extension\ElixirExtension;

$elixir = new ElixirExtension(
    $publicDir,     // the absolute public directory 
    $buildDir,      // the elixir build directory (default value is 'build')
    $manifestName   // the manifest filename (default value is 'rev-manifest.json')
);
$twig->addExtension($elixir);

Register the extension as a Symfony Service

# app/config/services.yml
services:
    app.twig_elixir_extension:
        class: BrieucThomas\Twig\Extension\ElixirExtension
        arguments: ["%kernel.root_dir%/../web/"]
        public: false
        tags:
            - { name: twig.extension }

Create a gulpfile

Here an example of gulpfile.js to compile and version the script app/Resources/js/app.js :

// gulpfile.js
const elixir = require('laravel-elixir');

elixir.config.assetsPath = 'app/Resources';
elixir.config.publicPath = 'web';
elixir.config.appPath = 'src';
elixir.config.viewPath = 'app/Resources/views';

elixir(function(mix) {
    // compile scripts to web/js/all.js (default output)
    mix.scripts(['app.js']);

    // version compiled scripts        
    mix.version(['js/all.js']);
});

Using the Extension

<link rel="stylesheet" href="{{ elixir('css/all.css') }}">
<script src="{{ elixir('js/all.js') }}"></script>

You can surround with the asset twig extension to make your application more portable:

<link rel="stylesheet" href="{{ asset(elixir('css/all.css')) }}">
<script src="{{ asset(elixir('js/all.js')) }}"></script>