liip / frctl-twig
Alias-Loader for handling fractal @handle's in twig and callable handler for the accompanied node module
Installs: 6 018
Dependents: 0
Suggesters: 0
Security: 0
Stars: 8
Watchers: 7
Forks: 5
Open Issues: 3
Requires
- twig/twig: ^1.24
This package is auto-updated.
Last update: 2024-11-12 20:37:36 UTC
README
frctl-twig is an adapter consisting of an NPM and a Composer package. It integrates the Twig PHP template engine into fractal.
Installation
Inside your fractal project add a composer package by adding a composer.json:
{
"name": "my/fractal-project",
"type": "project",
"require-dev": {
"liip/frctl-twig": "dev-master"
},
}
Run composer install
.
Add a devDependencies
to the fractal twig adapter into your package.json:
"frctl-twig": "git+https://github.com/liip/frctl-twig.git#master"
Run npm install
.
Adding Twig Extensions
Add any relevant composer packages to your composer.json.
For exampe run composer require twig/twig-extensions
.
Then add a file php-twig/TwigExtensions.php
to your fractal project with the following content:
<?php
namespace Frctl;
class TwigExtensions
{
static public function getExtensions()
{
return [
# Add your extensions here, for example the twig-extension text extension
# new \Twig_Extensions_Extension_Text(),
];
}
}
Then add the following section to your fractal project composer.json:
"autoload": {
"psr-4": {
"Frctl\\": "php-twig/"
}
}
How to use Twig templates in another project
Add the composer package pointing to your fractal project into the composer project of this other project.
Adjust the file loader to be able to find the twig templates in the fractal project:
class TwigFilesystemLoader extends BaseTwigFilesystemLoader
{
/**
* Should probably be set via a setter from configuration
*
* @var string
*/
private $fractalPath = '/path/to/fractal/twig/templates';
/**
* @param string $name
*
* @return string
*/
protected function findTemplate($name)
{
$fractalPath = $this->getFractalPath();
if ($fractalPath && preg_match('/^@fractal-(.*)$/', $name, $templatePath)) {
$fullFilePath = $fractalPath . '/' . $templatePath[1];
return $fullFilePath;
}
...
}
}
Load all the extensions into your Twig_Environment
instance:
if (class_exists('Frctl\TwigExtensions')) {
$extensions = \Frctl\TwigExtensions::getExtensions();
foreach ($extensions as $extension) {
$twig->addExtension($extension);
}
}
strict_variables
and debug
config flags
By default, the strict_variables
flag of twig is set to false
and the debug
flag is set to true.
To change these variables, pass them in an optional config object with their desired values while configuring
fractal:
const frctlTwig = require("frctl-twig");
fractal.components.engine(frctlTwig({
strict_variables: true, // Or false
debug: false // Or true
}));
// Further setup...
Credits
The code is based on the work by Benjamin Milde: