yafou/visuel

dev-main 2020-11-19 19:55 UTC

This package is auto-updated.

Last update: 2022-09-19 23:46:56 UTC


README

A simple and powerful PHP template engine

Summary

Getting started

  1. Install the package with Composer
    $ composer require yafou/visuel
  2. Create the renderer
    use YaFou\Visuel\Loader\FilesystemLoader;
    use YaFou\Visuel\Renderer;
    
    $loader = new FilesystemLoader(__DIR__.'/templates');
    $renderer = new Renderer($loader);
  3. Create the template in templates/home.visuel.php
    <h1>{{ $message }}</h1>
    
    <ul>
       @foreach($posts as $post)
           <li>
               <a href="{{ path($post) }}">{{ $post->getName() }}</a>
           </li>
       @endforeach
    </ul>
  4. Render the template
    echo $renderer->render('home.visuel.php', [
       'message' => 'Hello world!',
       'posts' => $repository->getAll()
    ]);

Features

Syntax

Print statement

Print statement:

{{ $variable }}
{{ trim($variable->method()) }}

Print statements use PHP, so all your methods and functions will be available.

Blocks

A block start with @ and a name: @if, @foreach...

Condition blocks
@if(<condition>)
...
@endif
@if($post->isPublic())
    {{ $post->getName() }}
@endif($post->isDraft() && $post->getAuthor() === $user)
    {{ $post->getName() }} (in draft)
@else
    You can't see this project
@endif
Foreach block
@foreach($posts as $post)
    <a href="{{ path($post) }}">{{ $post->getName() }}</a>
@else
    No posts ;(
@endforeach

Enable the cache

use YaFou\Visuel\Renderer;
use YaFou\Visuel\Cache\FilesystemCache;

$cache = new FilesystemCache(__DIR__.'/cache');
$renderer = new Renderer($loader, $cache);

Use a custom lexer

You can customize the default lexer used by Visuel:

use YaFou\Visuel\Lexer;
use YaFou\Visuel\Token;
use YaFou\Visuel\Renderer;

$lexer = new Lexer([
    Token::PRINT_START => '{-',
    Token::PRINT_END => '-}'
]);

$renderer = new Renderer($loader, null, $lexer);

Now you can use your custom tokens:

{- $message -}

However, you can create your custom lexer with the LexerInterface.

use YaFou\Visuel\LexerInterface;
use YaFou\Visuel\Source;
use YaFou\Visuel\TokenStream;

class MyCustomLexer implements LexerInterface
{
    public function tokenize(Source $source) : TokenStream{
        return new TokenStream(<tokens>)
    }
}

License

This project is under the MIT license.