README.md
TwigView plugin for CakePHP
This plugin for version 3 the CakePHP Framework allows you to use the Twig Templating Language for your views.
In addition to enabling the use of most of Twig's features, the plugin is tightly integrated with the CakePHP view renderer giving you full access to helpers, objects and elements.
Installation
To install via Composer, use the command below, it will automatically detect the latest version and bind it with ~
.
composer require wyrihaximus/twig-view
Configuration
Load Plugin
Add the following to your config/bootstrap.php
to load the plugin.
Plugin::load('WyriHaximus/TwigView', [
'bootstrap' => true,
]);
Use View class
Instead of extending from the View
let AppView
extend TwigView
:
namespace App\View;
use WyriHaximus\TwigView\View\TwigView;
class AppView extends TwigView
{
}
Quick Start
Load Helpers
In Controller/AppController
load your helpers:
public $helpers = ['Html', 'Form']; // And more
Or in your AppView file :
public function initialize()
{
parent::initialize();
$this->loadHelper('Html');
$this->loadHelper('Form');
}
Note: TwigView will look for its templates with the extension .twig
and then for .tpl
(deprecated).
Layout
Replace Template/Layout/default.ctp
by this Layout/default.twig
<!DOCTYPE html>
<html>
<head>
{{ Html.charset()|raw }}
<title>
{{ __('myTwigExample') }}
{{ _view.fetch('title')|raw }}
</title>
{{ Html.meta('icon')|raw }}
{{ Html.css('default.app.css')|raw }}
{{ Html.script('app')|raw }}
{{ _view.fetch('meta')|raw }}
{{ _view.fetch('css')|raw }}
{{ _view.fetch('script')|raw }}
</head>
<body>
<header>
{{ _view.fetch('header')|raw }}
</header>
{{ Flash.render()|raw }}
<section>
<h1>{{ _view.fetch('title')|raw }}</h1>
{{ _view.fetch('content')|raw }}
</section>
<footer>
{{ _view.fetch('footer')|raw }}
</footer>
</body>
</html>
Template View
Create a template, for exemple Template/Users/index.twig
like this
{{ _view.assign('title', __("I'm title")) }}
{{ _view.start('header') }}
<p>I'm header</p>
{{ _view.end() }}
{{ _view.start('footer') }}
<p>I'm footer</p>
{{ _view.end() }}
<p>I'm content</p>
Usage
Use $this
With twig $this
is replaced by _view
For example, without using Twig writing
<?= $this->fetch('content') ?>
But with Twig
{{ _view.fetch('content')|raw }}
Helpers
Any helper you defined in your controller.
public $helpers = ['Html', 'Form']; // ...
Can be access by their CamelCase name, for example creating a form using the FormHelper
:
{{ Html.link('Edit user', {'controller':'Users', 'action': 'edit' ~ '/' ~ user.id}, {'class':'myclass'})|raw }}
Elements
Basic
{% element 'Element' %}
With variables or options
{% element 'Plugin.Element' {
dataName: 'dataValue'
} {
optionName: 'optionValue'
} %}
Cells
Store in context then echo it
{% cell cellObject = 'Plugin.Cell' {
dataName: 'dataValue'
} {
optionName: 'optionValue'
} %}
{{ cellObject|raw }}
Fetch and directly echo it
{% cell 'Plugin.Cell' {
dataName: 'dataValue'
} {
optionName: 'optionValue'
} %}
Extends
If i want extend to Common/demo.twig
<div id="sidebar">
{% block sidebar %}{% endblock %}
</div>
<div id="content">
{% block body %}{% endblock %}
</div>
We can write in a view
{% extends 'Common/demo' %}
{% block sidebar %}
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
{% endblock %}
{% block body %}
{{ _view.assign('title', __("I'm title")) }}
{{ _view.start('header') }}
<p>I'm header</p>
{{ _view.end() }}
{{ _view.start('footer') }}
<p>I'm footer</p>
{{ _view.end() }}
<p>I'm content</p>
{% endblock %}
Note : the block body
is required, it's equivalent to <?= $this->fetch('content') ?>
Filters
debug
maps to <code>debug</code>pr
maps topr
low
maps to <code>low</code>up
maps to <code>up</code>env
maps to <code>env</code>count
maps to <code>count</code>pluralize
maps to <code>Cake\Utility\Inflector::pluralize</code>singularize
maps to <code>Cake\Utility\Inflector::singularize</code>camelize
maps to <code>Cake\Utility\Inflector::camelize</code>underscore
maps to <code>Cake\Utility\Inflector::underscore</code>humanize
maps to <code>Cake\Utility\Inflector::humanize</code>tableize
maps to <code>Cake\Utility\Inflector::tableize</code>classify
maps to <code>Cake\Utility\Inflector::classify</code>variable
maps to <code>Cake\Utility\Inflector::variable</code>slug
maps to <code>Cake\Utility\Inflector::slug</code>toReadableSize
maps to <code>Cake\I18n\Number::toReadableSize</code>fromReadableSize
maps to <code>Cake\I18n\Number::fromReadableSize</code>toPercentage
maps to <code>Cake\I18n\Number::toPercentage</code>number_format
maps to <code>Cake\I18n\Number::format</code>formatDelta
maps to <code>Cake\I18n\Number::formatDelta</code>currency
maps to <code>Cake\I18n\Number::currency</code>substr
maps to <code>substr</code>tokenize
maps to <code>Cake\Utility\Text::tokenize</code>insert
maps to <code>Cake\Utility\Text::insert</code>cleanInsert
maps to <code>Cake\Utility\Text::cleanInsert</code>wrap
maps to <code>Cake\Utility\Text::wrap</code>wrapBlock
maps to <code>Cake\Utility\Text::wrapBlock</code>wordWrap
maps to <code>Cake\Utility\Text::wordWrap</code>highlight
maps to <code>Cake\Utility\Text::highlight</code>tail
maps to <code>Cake\Utility\Text::tail</code>truncate
maps to <code>Cake\Utility\Text::truncate</code>excerpt
maps to <code>Cake\Utility\Text::excerpt</code>toList
maps to <code>Cake\Utility\Text::toList</code>stripLinks
maps to <code>Cake\Utility\Text::stripLinks</code>isMultibyte
maps toCake\Utility\Text::isMultibyte
utf8
maps toCake\Utility\Text::utf8
ascii
maps toCake\Utility\Text::ascii
parseFileSize
maps to <code>Cake\Utility\Text::parseFileSize</code>serialize
maps to <code>serialize</code>unserialize
maps to <code>unserialize</code>md5
maps to <code>md5</code>base64_encode
maps to <code>base64_encode</code>base64_decode
maps to <code>base64_decode</code>nl2br
maps to <code>nl2br</code>string
cast to <code>string</code>
Functions
in_array
maps to <code>in_array</code>explode
maps to <code>explode</code>array
cast to <code>array</code>array_push
maps to <code>push</code>array_add
maps to <code>add</code>array_prev
maps to <code>prev</code>array_next
maps to <code>next</code>array_current
maps to <code>current</code>array_each
maps to <code>each</code>__
maps to <code>__</code>__d
maps to <code>__d</code>__n
maps to <code>__n</code>__x
maps to <code>__x</code>__dn
maps to <code>__dn</code>defaultCurrency
maps to <code>Cake\I18n\Number::defaultCurrency</code>number_formatter
maps to <code>Cake\I18n\Number::formatter</code>uuid
maps to <code>Cake\Utility\Text::uuid</code>time
passed the first and optional second argument into <code>new \Cake\I18n\Time()</code>timezones
maps toCake\I18n\Time::listTimezones
elementExists
maps toCake\View\View::elementExists
,getVars
maps toCake\View\View::getVars
get
maps toCake\View\View::get
Twig
Visite Twig Documentaion for more tips
Extra included extensions
Events
This plugin emits several events.
Loaders
The default loader can be replace by listening to the WyriHaximus\TwigView\Event\LoaderEvent::EVENT
, for example with twital:
<?php
use Cake\Event\EventListenerInterface;
use Goetas\Twital\TwitalLoader;
use WyriHaximus\TwigView\Event\ConstructEvent;
use WyriHaximus\TwigView\Event\LoaderEvent;
class LoaderListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
LoaderEvent::EVENT => 'loader',
ConstructEvent::EVENT => 'construct',
];
}
public function loader(LoaderEvent $event)
{
$event->result = new TwitalLoader($event->getLoader());
}
/**
* We've also listening in on this event so we can add the needed extensions to check for to the view
*/
public function construct(ConstructEvent $event)
{
$event->getTwigView()->unshiftExtension('.twital.html');
$event->getTwigView()->unshiftExtension('.twital.xml');
$event->getTwigView()->unshiftExtension('.twital.xhtml');
}
}
Extensions
Extensions can be added to the twig environment by listening to the WyriHaximus\TwigView\Event\ConstructEvent::EVENT
, for example:
<?php
use Cake\Event\EventListenerInterface;
use WyriHaximus\TwigView\Event\ConstructEvent;
class LoaderListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
ConstructEvent::EVENT => 'construct',
];
}
public function construct(ConstructEvent $event)
{
$event->getTwig()->addExtension(new YourTwigExtension);
}
}
Bake
You can use Bake to generate your basic CRUD views using the theme
option.
Let's say you have a TasksController
for which you want to generate twig templates.
You can use the following command to generate your index, add, edit and view file formatted
using Twig :
bin/cake bake twig_template Tasks all -t WyriHaximus/TwigView
Screenshots
Profiler
Templates found
License
Copyright 2015 Cees-Jan Kiewiet
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.