Coder Social home page Coder Social logo

webpack-encore-twig's Introduction

Webpack Encore Twig Integration

Version PHP Version License Build Codecov StyleCI PHPStan Donate

Webpack Encore Standalone Twig Functions. Allows usage of Webpack Encore in Twig Templates without Symfony. Optimized for PHP-DI style containers.

This allows you to use the splitEntryChunks() and enableVersioning() features from Webpack Encore by reading the entrypoints.json and manifest.json files.

Installation

composer require lcharette/webpack-encore-twig

Documentation & Usage

Whenever you run Encore, two configuration files are generated in your output folder (default location: public/build/): entrypoints.json and manifest.json. Each file is similar, and contains a map to the final, versioned filenames.

The first file โ€“ entrypoints.json โ€“ is generated when the splitEntryChunks() option is defined in your webpack.config.js and will be read by the encore_entry_script_tags() and encore_entry_link_tags() Twig helpers this package provides. If you're using these, then your CSS and JavaScript files will render with the new, versioned filename.

The second file - manifest.json - is generated when Asset Versioning option (enableVersioning()) is defined in your webpack.config.js and will be read to get the versioned filename of other files, like font files or image files (though it also contains information about the CSS and JavaScript files).

Both features (splitEntryChunks() and enableVersioning()) are defined as two separate Twig Extensions (EntrypointsTwigExtension and VersionedAssetsTwigExtension respectively) in case you need/want to enable only one of the two.

splitEntryChunks and entrypoints.json

Encore writes an entrypoints.json file that contains all of the files needed for each "entry". To reference entries in Twig, you need to add the EntrypointsTwigExtension extension to the Twig Environment. This accept EntrypointLookup, which itself accept the path to the entrypoints.json, and the TagRenderer (which itself accept EntrypointLookup).

use Lcharette\WebpackEncoreTwig\EntrypointsTwigExtension;
use Lcharette\WebpackEncoreTwig\TagRenderer;
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookup;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$entryPoints = new EntrypointLookup('./path/to/entrypoints.json');
$tagRenderer = new TagRenderer($entryPoints);
$extension = new EntrypointsTwigExtension($entryPoints, $tagRenderer);

// Create Twig Environment and add extension
$loader = new FilesystemLoader('./path/to/templates');
$twig = new Environment($loader);
$twig->addExtension($extension);

Now, to render all of the script and link tags for a specific "entry" (e.g. entry1), you can:

{# any template or base layout where you need to include a JavaScript entry #}

{% block javascripts %}
    {{ parent() }}

    {{ encore_entry_script_tags('entry1') }}

    {# or render a custom attribute #}
    {#
    {{ encore_entry_script_tags('entry1', attributes={
        defer: true
    }) }}
    #}
{% endblock %}

{% block stylesheets %}
    {{ parent() }}

    {{ encore_entry_link_tags('entry1') }}
{% endblock %}

If you want more control, you can use the encore_entry_js_files() and encore_entry_css_files() methods to get the list of files needed, then loop and create the script and link tags manually.

Custom Attributes on script and link Tags

Custom attributes can be added to rendered script or link in 3 different ways:

  1. Via global config, using the defaultAttributes argument on the TagRenderer constructor, or using the setter method:

    $tagRenderer->setDefaultAttributes(['crossorigin' => 'anonymous']);
    
  2. Via specific script or link argument on the TagRenderer constructor, or using the setter method:

    $tagRenderer->setDefaultScriptAttributes(['defer' => null]);
    $tagRenderer->setDefaultLinkAttributes(['hreflang' => 'en']);
    
  3. When rendering in Twig - see the attributes option in the docs above.

enableVersioning and manifest.json

To read the manifest file to be able to link (e.g. via an img tag) to certain assets, you need to add the VersionedAssetsTwigExtension extension to the Twig Environment. This accept JsonManifest, which itself accept the path to the manifest.json.

use Lcharette\WebpackEncoreTwig\JsonManifest;
use Lcharette\WebpackEncoreTwig\VersionedAssetsTwigExtension;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$manifest = new JsonManifest('./path/to/manifest.json');
$extension = new VersionedAssetsTwigExtension($manifest);

// Create dumb Twig and test adding extension
$loader = new FilesystemLoader();
$twig = new Environment($loader);
$twig->addExtension($extension);

In your Twig template, just wrap each path in the Twig asset() function like normal:

<img src="{{ asset('build/images/logo.png') }}" alt="ACME logo">

Dependency Injection & Autowiring

When using a PSR Dependency Injection Container with autowiring, like PHP-DI, you can define EntrypointLookup and JsonManifest in your definition factory via their respective interface (EntrypointLookupInterface and JsonManifestInterface). For example :

use Lcharette\WebpackEncoreTwig\JsonManifest;
use Lcharette\WebpackEncoreTwig\JsonManifestInterface;
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookup;
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookupInterface;

// ...

return [
    EntrypointLookupInterface::class => function () {
        return new EntrypointLookup('./path/to/entrypoints.json');
    },
    JsonManifestInterface::class => function () {
        return new JsonManifest('./path/to/manifest.json');
    },
];

EntrypointsTwigExtension and VersionedAssetsTwigExtension can then be injected into your other classes via the container :

use Lcharette\WebpackEncoreTwig\EntrypointsTwigExtension;
use Lcharette\WebpackEncoreTwig\VersionedAssetsTwigExtension;

// ...

$extension = $container->get(EntrypointsTwigExtension::class);
$twig->addExtension($extension);

$extension = $container->get(VersionedAssetsTwigExtension::class);
$twig->addExtension($extension);

Using Without Twig

Both script and link tags can be generated in vanilla PHP and without Twig using the underlying public methods on the TagRenderer class:

Getting script and link tag from entrypoints.json:

$entryPoints = new EntrypointLookup('./path/to/entrypoints.json');
$tagRenderer = new TagRenderer($entryPoints);

// Returns the tags as string
$scriptsString = $tagRenderer->renderWebpackScriptTags('entry1');
$linksString = $tagRenderer->renderWebpackLinkTags('entry1');

// Returns the list of files as an array of strings
$jsFiles = $tagRenderer->getJavaScriptFiles('entry1');
$cssFiles = $tagRenderer->getCssFiles('entry1');

Same goes for the versioned assets, using the underlying public methods on the JsonManifest class:

Getting versioned from manifest.json:

$manifest = new JsonManifest('./path/to/manifest.json');
$path = $manifest->applyVersion('build/images/logo.png');

See Also

References

webpack-encore-twig's People

Contributors

lcharette avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Forkers

ncou

webpack-encore-twig's Issues

webpack-encore-bundle version 2

Hi there, thanks for the project!
We've been using it in the FOSSBilling project and all is working well, however I've noticed the package isn't yet updated to allow V2 of the symfony/webpack-encore-bundle package. v2 only dropped the deprecated functionality and increased the minimum PHP version, so all you need to do is update your composer.json file to allow both v1 and v2 of the package.

I've already validated that things work correctly with this upgrade in our application by leveraging composer's alias functionality ("2.1.1 as 1.17.2"), but that's not as nice of a solution as simply just having things work.

Thanks again!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.