Giter VIP home page Giter VIP logo

legacy-twig-view's Introduction

TwigView plugin for CakePHP

Build Status Latest Stable Version Total Downloads Code Coverage Software License

This plugin 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.

DEPRECATED: Use cakephp/twig-view instead.

Installation

To install via Composer, use the command below.

composer require wyrihaximus/twig-view

Configuration

Load Plugin

Run the following CLI command:

bin/cake plugin load WyriHaximus/TwigView

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

TwigView will look for its templates with the extension .twig.

Layout

Replace templates/layout/default.php by this templates/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 example templates/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 can be access by their CamelCase name, for example:

{{ 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

Functions

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(): array
    {
        return [
            LoaderEvent::EVENT => 'loader',
            ConstructEvent::EVENT => 'construct',
        ];
    }

    public function loader(LoaderEvent $event): void
    {
        $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): void
    {
        $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(): array
    {
        return [
            ConstructEvent::EVENT => 'construct',
        ];
    }

    public function construct(ConstructEvent $event): void
    {
        $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

Profiler

Templates found

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.

legacy-twig-view's People

Contributors

admad avatar arhell avatar batopa avatar bitdeli-chef avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dereuromark avatar didos avatar edggk avatar havokinspiration avatar iknowthis avatar imgbotapp avatar inoas avatar jadb avatar joshualuckers avatar lorenzo avatar m3nt0r avatar markstory avatar mechtecs avatar othercorey avatar ozee31 avatar peter279k avatar predominant avatar rewish avatar scrutinizer-auto-fixer avatar shama avatar steinkel avatar vonboth avatar wyrihaximus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

legacy-twig-view's Issues

Issue with Twig when trying to bake in cakephp 3.x

c:\wamp\www\landmarkcurrent\bin>cake bake all faculties
Bake All

One moment while associations are detected.
Exception: Unknown "as_array" filter. in [C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Template\Bake\Model\table.twig, line 50]
2018-04-12 12:22:52 Error: [Twig_Error_Syntax] Unknown "as_array" filter. in C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Template\Bake\Model\table.twig on line 50
Stack Trace:
#0 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\ExpressionParser.php(484): Twig_ExpressionParser->getFilterNodeClass('as_array', 50)
#1 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\ExpressionParser.php(469): Twig_ExpressionParser->parseFilterExpressionRaw(Object(Twig_Node_Expression_Name))
#2 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\ExpressionParser.php(323): Twig_ExpressionParser->parseFilterExpression(Object(Twig_Node_Expression_Name))
#3 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\ExpressionParser.php(215): Twig_ExpressionParser->parsePostfixExpression(Object(Twig_Node_Expression_Name))
#4 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\ExpressionParser.php(102): Twig_ExpressionParser->parsePrimaryExpression()
#5 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\ExpressionParser.php(55): Twig_ExpressionParser->getPrimary()
#6 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Parser.php(149): Twig_ExpressionParser->parseExpression()
#7 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\TokenParser\If.php(45): Twig_Parser->subparse(Array)
#8 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Parser.php(192): Twig_TokenParser_If->parse(Object(Twig_Token))
#9 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\TokenParser\If.php(36): Twig_Parser->subparse(Array)
#10 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Parser.php(192): Twig_TokenParser_If->parse(Object(Twig_Token))
#11 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Parser.php(105): Twig_Parser->subparse(NULL, false)
#12 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Environment.php(716): Twig_Parser->parse(Object(Twig_TokenStream))
#13 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Environment.php(774): Twig_Environment->parse(Object(Twig_TokenStream))
#14 C:\wamp\www\landmarkcurrent\vendor\twig\twig\lib\Twig\Environment.php(452): Twig_Environment->compileSource(Object(Twig_Source))
#15 C:\wamp\www\landmarkcurrent\vendor\wyrihaximus\twig-view\src\View\TwigView.php(180): Twig_Environment->loadTemplate('C:\wamp\www\lan...')
#16 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\View\BakeView.php(146): WyriHaximus\TwigView\View\TwigView->_render('C:\wamp\www\lan...')
#17 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Shell\Task\BakeTemplateTask.php(89): Bake\View\BakeView->render('Model/table')
#18 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Shell\Task\ModelTask.php(956): Bake\Shell\Task\BakeTemplateTask->generate('Model/table')
#19 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Shell\Task\ModelTask.php(114): Bake\Shell\Task\ModelTask->bakeTable(Object(Cake\ORM\Table), Array)
#20 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Shell\Task\ModelTask.php(100): Bake\Shell\Task\ModelTask->bake('Faculties')
#21 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Shell\BakeShell.php(272): Bake\Shell\Task\ModelTask->main('Faculties')
#22 C:\wamp\www\landmarkcurrent\vendor\cakephp\cakephp\src\Collection\CollectionTrait.php(51): Bake\Shell\BakeShell->Bake\Shell{closure}('faculties', 0)
#23 C:\wamp\www\landmarkcurrent\vendor\cakephp\bake\src\Shell\BakeShell.php(273): Cake\Collection\Collection->each(Object(Closure))
#24 C:\wamp\www\landmarkcurrent\vendor\cakephp\cakephp\src\Console\Shell.php(493): Bake\Shell\BakeShell->all('faculties')
#25 C:\wamp\www\landmarkcurrent\vendor\cakephp\cakephp\src\Console\CommandRunner.php(141): Cake\Console\Shell->runCommand(Array, true)
#26 C:\wamp\www\landmarkcurrent\bin\cake.php(12): Cake\Console\CommandRunner->run(Array)
#27 {main}

wyrihaximus/twig-view 5.0: Upgrade twig/twig 2.0

$ composer outdated shows me

aptoma/twig-markdown                  2.0.0   3.0.0   Twig extension to work with Markdown content
phpdocumentor/reflection-docblock     3.2.3   4.1.1   With this component, a library can provide support for annotations via DocBlocks or otherwise r...
twig/twig                             v1.34.4 v2.4.3  Twig, the flexible, fast, and secure template language for PHP

phpdocumentor/reflection-docblock is an indirect dependency to phpunit 6.3.0. The other outdated dependencies are indirect dependencies to TwigView.

Any idea when there will be made progress here?

What I'd suggest is: If there is a lot of manual, tedious labour, I can try to make the core TwigView run with Twig 2.0 and you/other contributors with more knowledge about Twig can take a look at my PRs and help out with the library dependencies of 3rd parties that need updating for Twig 2.0?

I am also interested because I hope to gain some performance benefits from going to Twig 2.0

How does it work on cakephp3 ?

Hi,

Here what i did :
Install via twigview via composer

composer require wyrihaximus/twig-view 
Using version dev-master for wyrihaximus/twig-view
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing twig/twig (v1.23.1)
    Downloading: 100%         

  - Installing asm89/twig-cache-extension (1.1.0)
    Downloading: 100%         

  - Installing wyrihaximus/twig-view (dev-master ac044a2)
    Cloning ac044a256c9cc29a30c402fcbd3c2cd1d214729e

Writing lock file
Generating autoload files

Load plugin in boostrap:

Plugin::load('Migrations');
Plugin::load('WyriHaximus/TwigView', [
    'bootstrap' => true,
]);

Initialise $viewClass :

src/Controller/AppController.php
class AppController extends Controller
{

    public $viewClass = '\WyriHaximus\TwigView\View\TwigView';
        .....
}

First little issue, these lines stop working

src/Template/Layout/default.ctp
<?= $this->fetch('meta') ?>
    <?= $this->fetch('css') ?>
    <?= $this->fetch('script') ?>

But the real probleme is assign variable and use it in template, I did:

src/Controller/AppController.php
class AppController extends Controller
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        $this->set('title',"test twig");

    }
}
src/Template/Layout/default.ctp
{{ title }}
<?= $this->fetch('content') ?>

And the render of variable is {{ title }} instead of test twig when i load the page on a browser.

Where is the mistake ? could you help me ?

Testing problem

Hi,

I have a problem when i test my controllers. All functions are unrecognized ("__()", "explode()" ...).
In my browser it's works.

In vendor/twig/twig/lib/Twig/Environment.php i have in $this->extensions
"core, escaper, optimizer, string_loader, debug, i18n ..."
But in test i have just :
"core, escaper and optimizer"

The class WyriHaximus\TwigView\Event\ExtensionsListener are not called by bootstrap.php (l.7) in test.

Do you have an explanation ? Thank You.

Call to a member function loadTemplate() on null

Just upgraded to Cake 3.5.8 and TwigView 4.2.6

My App breaks with 'Call to a member function loadTemplate() on null'

Error in: ROOT/vendor/wyrihaximus/twig-view/src/View/TwigView.php, line 188

For some reason the initialize()-Funktion in TwigView is not called.

Is this a CakePHP issue?

Using versions: 3.5.6 and 4.0.2 works just fine

I will investigate and post a solution if I find one ;-)

Documentation

Currently there is only a little bit of documentation. Expand it and also clean up the readme.

loadTemplate() on null

return $this->render('/Sofien/sofien', array('name' => $sof));

i get this error : Call to a member function loadTemplate() on null

how to fix ?

Dont find the index.tlp

Hi i follow your instructions and delete an index.ctp and replace for an index.tlp but dont recognize, what i have to do?

Do you have a project example in github maybe?

image

Name conflict with Twig default filter

TwigView 4.3.4

I want to use Twig's format filter.

{{ '#%07d' | format(order.id) }}

But, using this plugin will cause Cake\I18n\Number::format() to be called.

Is there a good way to call Twig's format?

mb_convert_encoding(): Illegal character encoding specified

When trying to use TwigView rendering, I got

mb_convert_encoding(): Illegal character encoding specified

in vendor/twig/twig/lib/Twig/Extension/Core.php:1137

Any idea what this is? It is a basic ascii template with simple variables.

	$data = [
		'name' => 'Foo',
		'namespace' => 'foo',
		'plugin' => 'cakephp-foo',
	];

	$this->renderer->set($data);

	$content = $this->renderer->generate('foo');

Disable Twig cache in debug mode

When CakePHP is in debug mode i.e. Configure::read('debug') === true the Twig cache should be disabled I think.

At the moment the cache is active by default and every time I edit a twig file then I need to cleanup the cache to see the changes.

Accessing Helpers

While trying the plugin, I found out I could not use the Helpers name directly as specified in the doc :

{{ Html.css('default.app.css')|raw }}

I had to call them as follows :

{{ _view.Html.css('default.app.css')|raw }}

After digging a bit, I found out that I had to change the TwigView::generateHelperList() method to the following implementation for it to work :

diff --git a/src/View/TwigView.php b/src/View/TwigView.php
index af8bc77..06ed785 100644
--- a/src/View/TwigView.php
+++ b/src/View/TwigView.php
@@ -164,7 +164,7 @@ protected function getLoader()
     protected function generateHelperList()
     {
         $registry = $this->helpers();
-        $helpers = $registry->normalizeArray($this->helpers);
+        $helpers = $registry->normalizeArray($registry->loaded());
         foreach ($helpers as $properties) {
             list(, $class) = pluginSplit($properties['class']);
             $this->helperList[$class] = $this->{$class};

I'm working with CakePHP 3.3-beta2 on a PHP 5.5.30 install.
I'm loading my Helpers in the initialize() method of my AppView class.

Is it ok if I submit a pull request with this change or do you think that could cause issues ?

Specialchar don't displayed with helper

I try to display a specialchar with a helper but doesn't work :

{{ Paginator.first('&laquo;')|raw }}
{{ Paginator.first('&laquo;'|e)|raw }}
{{ Paginator.first('&laquo;'|escape)|raw }}
{{ Paginator.first('&laquo;'|raw)|raw }}

Smarty filetype extension

It might be an odd question, but why are you using .tpl file extension instead of .twig? As far I can tell, .tpl is for the Smarty template syntax.

Thanks, and sorry if that's an stupid question.

Compile shell

Shell scans for templates and compiles them with Twig.

Using Twital

Would it be possible to use Twital with Cake + TwigView?

If so, are you able to explain how I should go about it?

Many thanks.

Deprecation error while running cake bake

While running any cake command in command line, we get the following error message.

Deprecated Error: Checking a single plugin with Plugin::loaded() is deprecated. Use Plugin::isLoaded() instead. - C:\path\to\project\vendor\wyrihaximus\twig-view\config\bootstrap.php, line: 11 You can disable deprecation warnings by setting Error.errorLevel to E_ALL & ~E_USER_DEPRECATED in your config/app.php. in [C:\path\to\project\vendor\cakephp\cakephp\src\Core\functions.php, line 311]

I know that the issue is fixed in this commit (8b0e05b), but can you tell me when a new release with this commit would be released? This is the last thing holding back our migration to CakePHP 3.7.0. We can always run the patch manually, but this would go against our deployment procedure which rely on the composer packages.

Thank you for your cooperation and feedback.

Problem with layout

Hi,

I have a problem with Layout

If use default.ctp with a twig view it's works but if i use a default layout with twig don't work (don't show de view, just show layout)

First test

<!-- layout.tpl -->
<h1>Hi</h1>

<!-- page.tpl -->
<p>Test</p>

Show just "Hi"

Second test

<!-- layout.tpl -->
<h1>Hi</h1>
{% block content %}{% endblock %}

<!-- page.tpl -->
<p>yo</p>
{% block content %}<p>test</p>{% endblock %}

Show just "Hi"

Other test

<!-- layout.tpl -->
<h1>Hi</h1>
{% block content %}{% endblock %}

<!-- page.tpl -->
{% extends 'Layout/default' %}

{% block content %}<p>test</p>{% endblock %}

Show just "Hi"

Thank you for your help

Events documentation

Describe how users can hook their own events to add extra extensions to Twig.

Not setting options for {% element %} throws error

Hi,

if you don't set options for element it will fail as it passes null to $compiler->subcompile()

in Lib\Twig\Node\Element.php
line: 65

$options = $this->getNode('options');
if ($data!== null) {
    $compiler->raw(',');
     $compiler->subcompile($options);
}

I think it should check for $options not $data.

Thanks.

replace Cake\Utility\String

Hi,
on cake 3.4.13 I get errors when using some filters. For example I tried to uses the 'tail'-filter and got:

call_user_func_array() expects parameter 1 to be a valid callback, class 'Cake\Utility\String' not found [ROOT/tmp/cache/twigView/92/92f2b8c028350aaa16ed3f034fd18af99b4bdbb3c04eb8818c6339fec8c6933b.php, line 76]

Cake\Utility\String is AFAIK replaced by Cake\Utility\Text ?

BTW: Thanks for this very helpful plugin!

Problem with extend common view

Hi,

I have a problem with Extending Views.

I have a layout default.tpl

<!DOCTYPE html>
<html>
<head>...</head>
<body>
    <header>
        {% if auth %}
            {% element 'nav' %}
        {% endif %}
        {{ _view.fetch('header')|raw }}
    </header>

    <section id="{{ page_id }}" class="js-container container-fluid">
        <div>
            {{ Flash.render()|raw }}
        </div>

        {{ _view.fetch('content')|raw }}
    </section>
</body>

In Common have a view content_sidebar.tpl

<div class="row">
    <div class="col-lg-2 col-md-3" style="background-color:green; height: 200px;">
        Sidebar
        {{ _view.fetch('sidebar')|raw }}
    </div>

    <div class="col-lg-10 col-md-9" styles="background-color:red; height: 200px;">
        Content
        {{ _view.fetch('content')|raw }}
    </div>
</div>

Extends this view in Users/view.tpl doesn't works

First test

{% extends 'Common/content_sidebar' %}

{{ _view.start('sidebar') }}
    <p>Hi</p>
{{ _view.end() }}

<p>Plop</p>

Result :
A template that extends another one cannot have a body in "/var/www/html/app/src/Template/Users/view.tpl" at line 6.

Second test

{{ _view.extend('/Common/content_sidebar') }}

{{ _view.start('sidebar') }}
    <p>Hi</p>
{{ _view.end() }}

<p>Plop</p>

Result :
Display just

Plop

, no display Common's view

Thank you for your help

Call to a member function loadTemplate() on null

I'm using CakePHP3 with TwigView. However, I can not load any page on my application. I get the following error at the src/View/TwigView.php file. What am I doing wrong?

Call to a member function loadTemplate() on null

I can not use .twig and .tpl extensions too.

The routing configuration:

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect(
      '/',
      ['controller' => 'Man', 'action' => 'login']
    );
    $routes->connect(
      '/man/*',
      ['controller' => 'Man', 'action' => 'login']
    );
    $routes->fallbacks(DashedRoute::class);
});

TwigView Setting

// file: src/View/AppView.php
namespace App\View;
use WyriHaximus\TwigView\View\TwigView;

class AppView extends TwigView
{
    public function initialize()
    {
    }
}

Application class Setting

// file Application.php
    class Application extends BaseApplication
    {
        /**
         * {@inheritDoc}
         */
        public function bootstrap()
        {
            $this->addPlugin('WyriHaximus/TwigView');
            ....
        }
    }

Layout file

// file: Template/Layout/default.tpl

Controller

class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();
        $this->viewBuilder()->setLayout("default");
    }
}

Step by Step Example

Hello i am completly new to cakephp. Could you provide me an example how to get the view rendered in my controller?

I added these lines to my bootstrap file

Plugin::load('WyriHaximus/TwigView', [
    'bootstrap' => true,
]);

Using include function

I've tried to use {{ include('template.html') }} but am getting Template "template.html" is not defined.
Is there a way to get the include function to work?

The unit tests will be failed on CakePHP 4.1.x version

Reproducing issues

  • Firstly, using git clone command to clone this repository.
  • Using the composer command with php-7.2+ version to install dependencies.
  • Using the composer show | grep cakephp command to check related CakePHP dependencies:
cakephp/cakephp                       4.1.3   The CakePHP framework
cakephp/cakephp-codesniffer     4.2.2   CakePHP CodeSniffer Standards
cakephp/chronos                       2.0.5   A simple API extension for ...
cakephp/debug_kit                     4.3.2   CakePHP Debug Kit
  • Run vendor/bin/phpunit command to run unit tests.

Expected

  • There's no error output during above PHPUnit command running.

Actual

  • The PHPUnit command running reports following error:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.
Runtime:       PHP 7.3.21 with PCOV 1.0.6
Configuration: /home/travis/build/open-source-contributions/legacy-twig-view/phpunit.xml.dist
......................F.........................................Compiling all templates
Compiling APP's templates
/home/travis/build/open-source-contributions/legacy-twig-view/tests/test_app/templates/Blog/index.twig
/home/travis/build/open-source-contributions/legacy-twig-view/tests/test_app/templates/element/element.twig
/home/travis/build/open-source-contributions/legacy-twig-view/tests/test_app/templates/exception.twig
/home/travis/build/open-source-contributions/legacy-twig-view/tests/test_app/templates/layout.twig
/home/travis/build/open-source-contributions/legacy-twig-view/tests/test_app/templates/layout/layout.twig
/home/travis/build/open-source-contributions/legacy-twig-view/tests/test_app/templates/syntaxerror.twig
. 65 / 79 ( 82%)
Compiling one bar:foo's templates
.Compiling one template
foo:bar
..SSSSS......                                                    79 / 79 (100%)
Time: 247 ms, Memory: 16.00 MB
There was 1 failure:
1) WyriHaximus\TwigView\Test\Lib\Twig\Extension\BasicTest::testFilterDebug
Failed asserting that two strings are identical.
--- Expected
+++ Actual
@@ @@
-'
-########## DEBUG ##########
-'abc'
-###########################
+'
+########## DEBUG ##########
+'abc'
+###########################
 '
/home/travis/build/open-source-contributions/legacy-twig-view/tests/Lib/Twig/Extension/BasicTest.php:33
--

Probable issue fixing

If letting "cakephp/cakephp": "~4.0.0",, "cakephp/cakephp-codesniffer": "~4.0.0", and "cakephp/debug_kit": "~4.0.0", be defined on composer.json, it will be following dependencies installed via composer show | grep cakephp:

cakephp/cakephp                       4.0.9   The CakePHP framework
cakephp/cakephp-codesniffer           4.0.1   CakePHP CodeSniffer Standards
cakephp/chronos                       2.0.5   A simple API extension for ...
cakephp/debug_kit                     4.0.6   CakePHP Debug Kit
cakephp/plugin-installer              1.2.0   A composer installer for Ca...

And it will be successful during PHPUnit command running:

PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

................................................................Compiling all templates
Compiling APP's templates
/data/legacy-twig-view/tests/test_app/templates/Blog/index.twig
/data/legacy-twig-view/tests/test_app/templates/element/element.twig
/data/legacy-twig-view/tests/test_app/templates/exception.twig
/data/legacy-twig-view/tests/test_app/templates/layout.twig
/data/legacy-twig-view/tests/test_app/templates/layout/layout.twig
/data/legacy-twig-view/tests/test_app/templates/syntaxerror.twig
. 65 / 79 ( 82%)
Compiling one bar:foo's templates
.Compiling one template
foo:bar
..SSSSS......                                                    79 / 79 (100%)

I'm not sure why the PHPUnit command running is failed on cakephp/cakephp:4.1.x version, but I think it should let cakephp/cakephp be 4.0.x strictly.

add missing inflectors

the newer ones seem missing as filter:

  • dasherize maps to Cake\Utility\Inflector::dasherize()
  • slug should be Text:slug() as Inflector::slug() is deprecated

also:

  • autoParagraph => TextHelper::autoParagraph()
  • autoLinkUrls => TextHelper::autoLinkUrls()

Dependabot can't resolve your PHP dependency files

Dependabot can't resolve your PHP dependency files.

As a result, Dependabot couldn't update your dependencies.

The error Dependabot encountered was:

The "https://repo.packagist.org/packages.json" file could not be downloaded: failed to open stream: Network is unreachable

If you think the above is an error on Dependabot's side please don't hesitate to get in touch - we'll do whatever we can to fix it.

You can mention @dependabot in the comments below to contact the Dependabot team.

Deprecations warnings

Hi, I have deprecations warnings that I can't find.
I've scanned my project using PhpStorm to find deprecation usages without success.
Is TwigView plugin up to date with CakePhp deprecations ?

Thanks.

src/Template.php:529 
The ArrayAccess methods will be removed in 4.0.0.Use getParam() instead. - /Applications/MAMP/htdocs/my_app/vendor/twig/twig/src/Template.php, line: 529 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.
src/Template.php:595 
Accessing query as a property will be removed in 4.0.0. Use getQuery() instead. - /Applications/MAMP/htdocs/my_app/vendor/twig/twig/src/Template.php, line: 595 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.
src/Template.php:604 
Accessing `query` as a property will be removed in 4.0.0. Use request->getQuery() instead. - /Applications/MAMP/htdocs/my_app/vendor/twig/twig/src/Template.php, line: 604 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.
src/Template.php:529 
The ArrayAccess methods will be removed in 4.0.0.Use getParam() instead. - /Applications/MAMP/htdocs/my_app/vendor/twig/twig/src/Template.php, line: 529 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.
src/Template.php:595 
Accessing query as a property will be removed in 4.0.0. Use getQuery() instead. - /Applications/MAMP/htdocs/my_app/vendor/twig/twig/src/Template.php, line: 595 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.
src/Template.php:604 
Accessing `query` as a property will be removed in 4.0.0. Use request->getQuery() instead. - /Applications/MAMP/htdocs/my_app/vendor/twig/twig/src/Template.php, line: 604 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.

Warning with cakephp3.5

Hello,

When i run TwigView on a CakePhp 3.5, with this code,

{{ _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>

i got those warnings :

Warning (4096): Object of class App\View\AppView could not be converted to string [ROOT/tmp/cache/twigView/93/9354f08c1f47e54248409d9f11b74ab4e9f9d332c0df7ef5d38a4a486cb660cb.php, line 27]
I'm header

I'm title

Warning (4096): Object of class App\View\AppView could not be converted to string [ROOT/tmp/cache/twigView/93/9354f08c1f47e54248409d9f11b74ab4e9f9d332c0df7ef5d38a4a486cb660cb.php, line 22]
Warning (4096): Object of class App\View\AppView could not be converted to string [ROOT/tmp/cache/twigView/93/9354f08c1f47e54248409d9f11b74ab4e9f9d332c0df7ef5d38a4a486cb660cb.php, line 32]
Warning (4096): Object of class App\View\AppView could not be converted to string [ROOT/tmp/cache/twigView/93/9354f08c1f47e54248409d9f11b74ab4e9f9d332c0df7ef5d38a4a486cb660cb.php, line 42]
I'm content

Warning (4096): Object of class App\View\AppView could not be converted to string [ROOT/tmp/cache/twigView/93/9354f08c1f47e54248409d9f11b74ab4e9f9d332c0df7ef5d38a4a486cb660cb.php, line 37]
I'm footer


Everything works fine with Cake3.4

Mitch

Unknown "getVars" function

When I attempt to run {% do getVars()|debug %} in my twig file, I get the following error:

Exception: Unknown "getVars" function. in [/path/to/app/plugins/MyPlugin/src/Template/Bake//Model/entity.twig, line 17]

entity.twig

Line 17: {% do getVars()|debug %}

Here is the full trace:

$ ./cake bake model all -t MyPlugin
One moment while associations are detected.

Baking table class for CommitmentItems...

File `/path/to/app/src/Model/Table/CommitmentItemsTable.php` exists
Do you want to overwrite? (y/n/a/q)
[n] > a
Wrote `/path/to/app/src/Model/Table/CommitmentItemsTable.php`
Exception: Unknown "getVars" function. in [/path/to/app/plugins/MyPlugin/src/Template/Bake//Model/entity.twig, line 17]
2019-12-19 15:28:16 Error: [Twig\Error\SyntaxError] Unknown "getVars" function. in /path/to/app/plugins/MyPlugin/src/Template/Bake//Model/entity.twig on line 17
Stack Trace:
#0 /path/to/app/vendor/twig/twig/src/ExpressionParser.php(461): Twig\ExpressionParser->getFunctionNodeClass('getVars', 17)
#1 /path/to/app/vendor/twig/twig/src/ExpressionParser.php(243): Twig\ExpressionParser->getFunctionNode('getVars', 17)
#2 /path/to/app/vendor/twig/twig/src/ExpressionParser.php(183): Twig\ExpressionParser->parsePrimaryExpression()
#3 /path/to/app/vendor/twig/twig/src/ExpressionParser.php(78): Twig\ExpressionParser->getPrimary()
#4 /path/to/app/vendor/twig/twig/src/TokenParser/DoTokenParser.php(26): Twig\ExpressionParser->parseExpression()
#5 /path/to/app/vendor/twig/twig/src/Parser.php(209): Twig\TokenParser\DoTokenParser->parse(Object(Twig\Token))
#6 /path/to/app/vendor/twig/twig/src/Parser.php(122): Twig\Parser->subparse(NULL, false)
#7 /path/to/app/vendor/twig/twig/src/Environment.php(735): Twig\Parser->parse(Object(Twig\TokenStream))
#8 /path/to/app/vendor/twig/twig/src/Environment.php(793): Twig\Environment->parse(Object(Twig\TokenStream))
#9 /path/to/app/vendor/twig/twig/src/Environment.php(482): Twig\Environment->compileSource(Object(Twig\Source))
#10 /path/to/app/vendor/twig/twig/src/Environment.php(445): Twig\Environment->loadClass('__TwigTemplate_...', '/srv/www/htdocs...', NULL)
#11 /path/to/app/vendor/wyrihaximus/twig-view/src/View/TwigView.php(180): Twig\Environment->loadTemplate('/srv/www/htdocs...')
#12 /path/to/app/vendor/cakephp/bake/src/View/BakeView.php(146): WyriHaximus\TwigView\View\TwigView->_render('/srv/www/htdocs...')
#13 /path/to/app/vendor/cakephp/bake/src/Shell/Task/BakeTemplateTask.php(91): Bake\View\BakeView->render('Model/entity')
#14 /path/to/app/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(968): Bake\Shell\Task\BakeTemplateTask->generate('Model/entity')
#15 /path/to/app/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(116): Bake\Shell\Task\ModelTask->bakeEntity(Object(App\Model\Table\CommitmentItemsTable), Array)
#16 /path/to/app/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(101): Bake\Shell\Task\ModelTask->bake('CommitmentItems')
#17 /path/to/app/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(171): Bake\Shell\Task\ModelTask->main('commitment_item...')
#18 /path/to/app/vendor/cakephp/cakephp/src/Console/Shell.php(517): Bake\Shell\Task\ModelTask->all()
#19 /path/to/app/vendor/cakephp/cakephp/src/Console/Shell.php(524): Cake\Console\Shell->runCommand(Array, false, Array)
#20 /path/to/app/vendor/cakephp/cakephp/src/Console/CommandRunner.php(385): Cake\Console\Shell->runCommand(Array, true)
#21 /path/to/app/vendor/cakephp/cakephp/src/Console/CommandRunner.php(162): Cake\Console\CommandRunner->runShell(Object(Bake\Shell\BakeShell), Array)
#22 /path/to/app/bin/cake.php(12): Cake\Console\CommandRunner->run(Array)
#23 {main}

Roadmap v5.0

Todo:

  • Twig 3.0
  • Bump minimum PHP version to 7.1
  • Merge in all changes from the 4.x branch
  • Clean up and reorganize filters and functions

Research:

  • Disable autoescaping for functions and filters so |raw everywhere isn't required (via @markstory)

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.