mehrkanal/twig-encore-extension

Twig Extension to use entrypoints.json in Twig Templates

4.0.2 2023-06-27 11:37 UTC

This package is not auto-updated.

Last update: 2024-05-08 23:20:02 UTC


README

To use with twig/twig and symfony/webpack-encore-bundle

Created for: Laminas/Mezzio Applications without native Symfony Kernel.
Warning: If Symfony is available, just use the symfony/webpack-encore-bundle bundle as is.

How to use and configure Encore

  1. composer require symfony/webpack-encore-bundle
  2. npm i @symfony/webpack-encore
  3. webpack.config.js
    • setOutputPath() should be in the public folder
      • i.e. .setOutputPath('public/assets')
    • setPublicPath() should be in the folder where the assets are in
      • i.e. setPublicPath('/assets')
  4. Set ['twig']['asset_url'] to the absulute Path, for example in your twig.global.php
    • Best be set to: /app/public/assets/
    • Note: A Forward Slash is appended after asset_url in case the preceding path does not end on a forward slash
      • i.e. asset_path is /assets the url will be <document_root>/assets/entrypoints.json
  5. Include Mehrkanal\EncoreTwigExtension\ConfigProvider::class into your global config
  6. Include Mehrkanal\EncoreTwigExtension\Extensions\GetCssSourceTwigExtension:class to your ['twig']['extensions'] config.
  7. Include \Symfony\Bridge\Twig\Extension\AssetExtension::class to your ['twig']['extensions'] config.
  8. Include Symfony\WebpackEncoreBundle\Twig\EntryFilesTwigExtension:class to your ['twig']['extensions'] config.
use Mehrkanal\EncoreTwigExtension\Extensions\GetCssSourceTwigExtension;
use Symfony\WebpackEncoreBundle\Twig\EntryFilesTwigExtension;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

require_once 'vendor/autoload.php';
$container = require __DIR__ . '/container.php';

$loader = new FilesystemLoader('./templates');
$twig = new Environment($loader, [
	'debug' => true
]);

$twig->addExtension($container->get(EntryFilesTwigExtension::class));
$twig->addExtension($container->get(GetCssSourceTwigExtension::class));

What can I do now?

  • Use Encore NodeJS Scripts to automatically generate assets
  • Use encore_entry_link_tags(<entrypoint>) function in Twig to get all required stylesheet link tags
  • Use encore_entry_script_tags(<entrypoint>) function in Twig to get all required script tags
  • Use encore_get_css_source(<entrypoint>) function in Twig to get all CSS Code from this entrypoint

Use in combination with setEntry of Encore Webpack Config.

Stan

docker run -it -v $PWD:/app -v $SSH_AUTH_SOCK:$SSH_AUTH_SOCK -w /app -e SSH_AUTH_SOCK=$SSH_AUTH_SOCK -e SSH_AGENT_PID=$SSH_AGENT_PID registry.mehrkanal.com/docker/phpx/cli:8.1-build bash

composer up
composer run stan
composer run cf

Useful links:

Team

MKLabs