Code Monkey home page Code Monkey logo

zfctwig's Introduction

ZfcTwig Module for Zend Framework 2 Master Branch Build Status

ZfcTwig is a module that integrates the Twig templating engine with Zend Framework 2.

Installation

  1. Add "zf-commons/zfc-twig": "dev-master" to your composer.json file and run php composer.phar update.
  2. Add ZfcTwig to your config/application.config.php file under the modules key.

Configuration

ZfcTwig has sane defaults out of the box but offers optional configuration via the zfctwig configuration key. For detailed information on all available options see the module config file class.

Documentation

Setting up Twig extensions

Extensions can be registered with Twig by adding the FQCN to the extensions configuration key which is exactly how the ZfcTwig extension is registered.

// in module configuration or autoload override
return array(
    'zfctwig' => array(
        'extensions' => array(
            // an extension that uses no key
            'My\Custom\Extension',

            // an extension with a key so that you can remove it from another module
            'my_custom_extension' => 'My\Custom\Extension'
        )
    )
);

Configuring Twig loaders

By default, ZfcTwig uses a Twig_Loader_Chain so that loaders can be chained together. A convenient default is setup using a filesystem loader with the path set to module/Application/view which should work out of the box for most instances. If you wish to add additional loaders to the chain you can register them by adding the service manager alias to the loaders configuration key.

// in module configuration or autoload override
return array(
    'zfctwig' => array(
        'loaders' => array(
            'MyTwigFilesystemLoader'
        )
    )
);

// in some module
public function getServiceConfiguration()
{
    return array(
        'factories' => array(
            'MyTwigFilesystemLoader' => function($sm) {
                return new \Twig_Loader_Filesystem('my/custom/twig/path');
            }
        )
    );
}

Using ZF2 View Helpers

Using ZF2 view helpers is supported through the ZfcTwig\Twig\FallbackFunction function.

{# Simple view helper echo #}
{{ docType() }}

{# Echo with additional methods #}
{{ headTitle('My Company').setSeparator('-') }}

{# Using a view helper without an echo #}
{% do headTitle().setSeparator('-') %}

{# Combining view helpers #}
{% set url = ( url('my/custom/route') ) %}

Examples

Example .twig files for the skeleton application can be found in the examples folder.

Gotchas

ZF2 does not support multiple renderers with view helpers very well. As a workaround, ZfcTwig registers its own HelperPluginManager that extends the default Zend\View\HelperPluginManager and adds the default as a peering manager. This let's ZfcTwig register its own renderer with view helpers that require it and fallback to the default manager for view helpers that do not require one.

As a caveat, you must register view helpers that require a renderer with ZfcTwig. An example can be seen in config/module.config.php where the HelperConfig for the default navigation helpers is registered with ZfcTwig.

zfctwig's People

Contributors

0legkolomiets avatar alexdenvir avatar bakura10 avatar cosmin-harangus avatar evandotpro avatar halaxa avatar hikaru-shindo avatar jonmorrison99 avatar kokspflanze avatar nikolay-kozlov avatar rmasters avatar saeven avatar sasezaki avatar spiffyjr avatar xoob 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  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

zfctwig's Issues

Issue with forms in ZF2 beta5

I'm trying to reproduce the howto provided by Matthew (http://mwop.net/blog/2012-07-02-zf2-beta5-forms.html) which works fine with the zendframework/ZendSkeletonApplication

Rendering the openTag and closeTag via

{{ form().openTag(form)|raw }}

{{ form().closeTag(form)|raw }}

work fine, however rendering a form element via

{{ formRow(form.get('name'))|raw }}

result in an exception when ZFCTwig is enabled

Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message
 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for form_label' in
C:\wamp\www\solodb\vendor\twig\twig\lib\Twig\Template.php on line 269

1.11.1 causes helpers (at least HeadScript and InlineScript) to break

You may be aware of this one already, but presently, 1.11.1 causes the layout provided in the zfctwig examples even, to die explaining that exceptions are being thrown in eval'd code:

Fatal error: Method Zend\View\Helper\HeadScript::__toString() must not throw an exception in Project/vendor/twig/twig/lib/Twig/Environment.php(327) : eval()'d code on line 229

Have quickly pinpointed it in \Zend\View\Helper\HeadScript at this line:

$useCdata = $this->view->plugin('doctype')->isXhtml() ? true : false;

zfctwig config is:

'zfctwig' => array(
    'namespaces' => array(
        'application'     => __DIR__ . '/../view',
    ),
    'disable_zf_model'           => false,
),

Form method is always post

I've created a simple action inside the ZF2Skeleton.
The action only creates a form and passes it to the view:

$form = new Form();
return array('form' => $form);

And on the view I only have this:
{{ form(form, {'method': 'GET'}) }}

When the page renders, the form method is always POST.
Is there any place where i can debug this?

Libraries versions:
twig/twig - v1.13.2
zendframework/zendframework - 2.2.4
zf-commons/zfc-twig - dev-master 20a55ba

Thanks

Absolutely unclear behaviour with 'disable_zf_model' => true in case of template errors

For example if in my action template I make mistake in path to base template (for example {% extend 'the/wrong/path/to/layout.twig' %}), actual Twig_Error_Loader exception 'Template layout.twig not found' will be catched and instead of error message I will receive the page generated from layout.twig template in legacy ZF2 template inheritance way, but of course without any content.

I have to debug my project to detect simply typo in template path. In my opinion this not good.

cant do composer update

I do php composer.phar with my json like this

{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for JP2",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"zf2"
],
"homepage": "http://plocal.sba.bcc.it:8080/",
"require": {
"php": ">=5.3.3",
"zendframework/zendframework": "dev-master",
"zf-commons/zfc-twig": "dev-master"
}
}

and the error was

missing layout

I just updated to 1.0.1 from 0.1 and my content is now displayed without a layout. I don't really have an idea why that is. Could you give me a clue about what the issue could be?

nameOrModel always assumes it's an object

When I was trying to analyze #59 I found in the following code that the function parameter nameOrModel always assumes it retrieved the view model. I am getting the error: Fatal error: Call to a member function getChildren() on a non-object.

The thing that causes is that I don't use the ZF2 built in layout system but I extend my action view:

{% extends 'layout/layout.twig' %}
{% block body %}
Dit is home :-)
{% endblock body %}

And of course in the template map layout/layout.twig exists. The page is half loading:

zfctwig

And in view/Renderer/TwigRenderer.php on line 191, there is assumed that nameOrModel is always an object, which isn't in my case.

HeadTitle ViewHelper appears broken

When using eg.

{% headTitle('sitename').setSeparator(' - ') %}
{% headTitle().append('mainTitle') %}

The 'mainTitle' part never gets appended to the title...

Clone of ViewHelperManager broke compatibility

In the new 1.1.4 version ViewHelperManager was cloned in Module.php

'ZfcTwigViewHelperManager' => function($sm) {
    // Clone the ViewHelperManager because each plugin has its own view instance.
    // If we don't clone it then the ViewHelpers use PhpRenderer.
    // This should really be changed in ZF Proper to call the event to determine which Renderer to use.
    //return clone $sm->get('ViewHelperManager');
    return clone $sm->get('ViewHelperManager');
},

this broke some modules like widmogrod/zf2-assetic-module which have had correct behavior

ZfcTwig and serviceManager

I need to recover the content of a view from a controller.
I try with this:

$view = $this->serviceManager->get('view');
$viewModel = new ViewModel();
$viewModel->setTemplate('emails/asd');
die(var_dump($view->render($viewModel)));

but it say:
Fatal error: Call to a member function setContent() on a non-object in /Users/Oscar/Sites/Gamempire/nightly/vendor/zf-commons/zfc-twig/src/ZfcTwig/View/Strategy.php on line 74

why?

Trying to config per README.md, and get There are no registered paths for namespace "__main__"

Module config in pertinent spot reads:

'view_manager' => array(

 'template_path_stack'      => array(
        'application'          => __DIR__ . '/../views',
    ),
    'template_map' => array(
        'layouts/layout'    => __DIR__ . '/../views/layouts/layout.twig',
        'index/index'          => __DIR__ . '/../views/application/index/index.twig',
    ),
 ),

'zfctwig' => array(
    'namespaces' => array(
        'application'     => __DIR__ . '/../views/application',
    ),
),

Have tried every permutation and combination I can think of..

Thanks for any guidance you can offer.

How to create a ZF2 module

Hello all users of ZF2

I'am a new user of ZF2 and i hope that i will use it until can create my own module.

Where may i begin , please ?.

Clarity on disable_zf_model after upgrade from 1.0 to 1.1

Hi

I upgraded from 1.0 to 1.1 and wanted to find out if the following should still work with disable_zf_model = true (it did work for me on version 1.0.*)

Inside the controller

public function manageAction()
{
    $clients = $this->forward()->dispatch('App\Controller\Client', array(...));
    $contacts = $this->forward()->dispatch('App\Controller\Contact', array(...));

    $viewModel = new ViewModel()
    return $viewModel
        ->addChild($clients, 'clientWidget')
        ->addChild($contacts, 'contactWidget');
}

and then the view

{% extends 'layout/admin.twig' %}
{% block content %}
<div class="tab-content">
<div class="tab-pane fade active in" id="clients">
{{ clientWidget|raw }}
</div>
<div class="tab-pane fade" id="contacts">
{{ contactWidget|raw }}
</div>
</div>
{% endblock content %}

I know I can convert both the forward calls to viewHelpers but I was just wondering. I do not particularly need them as helpers, but if the behaviour is not supported I'll convert the controller calls to helpers.

Many thanks

suffix_locked issue

I updated the module and it seems to be broken with suffix_locked=true. I didn't go into further detail, but it seems that Renderer::canRender paremeter "nameOrModel" should contain the extension name, but it does not.

module throw exception if some module hasn't view folder.

If some module hasn't view folder. then:

Fatal error: Uncaught exception 'Twig_Error_Loader' with message 'The "/www/libra-cms/vendor/libra/libra-locale/config/../view/" directory does not exist.' in /www/libra-cms/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 860

"layout/layout" error and disable_zf_model

In version 1.1.0 and later I getting this error:

"Zend\View\Renderer\PhpRenderer::render: Unable to render template "layout/layout"; resolver could not resolve to a file"

I have 'disable_zf_model' flag setted to true. I have not any file defined for "layout/layout" template map.

doesnt work with zf 2.2.1

I get this

Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "ZfcTwigViewStrategy"; no instance returned in ...
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "ZfcTwigRenderer"; no instance returned in....
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "ZfcTwigEnvironment"; no instance returned in ....
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "ZfcTwigLoaderChain"; no instance returned in .....

and that is all on one page.

Basically it says that the instance is not returned however i have checked the module.php and all should be correct.

I have to mention that the install was done thru composer

ZfcTwig does not pass correct Renderer to View Helpers

When using ZfcTwig - if you attempt to ->getView() within a view helper - you'll get back the default Renderer

Workaround is to implement ServiceManagerAwareInterface and add something like

$this->setView($this->services->get('TwigViewRenderer'));

to the __invoke() method.

View directory structure

Hello,

I'm using ZfcTwig now, but I have a problem with the structure of my view directory.
My Controllers are:

\Application\Controller\ArticleController
\Application\Controller\Admin\CommentController

But in the view directory this has the following structure:

views\article\add.twig
views\comment\add.twig

Is it possible to create a structure like this:

views\article\add.twig
views\article\admin\comment\add.twig

(In this example it isn't necessary, but the real project is al lot larger)

Thanks

"Cooperate" with other rendering strategies

At the moment it is not possible to have twig views and still use modules utilizing the PhpRenderer.

This is a crucial point because it is not practical to either rewrite every php view in these modules to twig nor to not use PhpRenderer based modules.

I may miss something but the documentation does not point out how to get this to work.

It should be possible to use a twig layout and still utilize other view strategies in some modules. I think this is a crucial feature to add, so ZfcTwig can become usable.

I encountered this behaviour using a skeleton application, adding ZfcTwig and ZfcUser and configuring both according to the docs.

Class 'ZfcTwig\View\Strategy\TwigStrategy' not found

Same fatal error as the user mdjaman, all is correct install with composer, files are there, configuration paramters are set - but see a empty page no content and in log file: "PHP Fatal error: Class 'ZfcTwig\View\Strategy\TwigStrategy' not found in /xxxx/zf2/vendor/ZfcTwig/src/ZfcTwig/Module.php on line 62"
Is run in the ZendSkeletonApplication. Are they any tips or ideas?

Thank you very much for help in advance

Fatal error: Class 'ZfcTwig\View\Strategy\TwigStrategy' not found

Hi can someone can help? i can't get ZfcTwig to work, i configure everything from Readme.md but only got this fatal error return
Fatal error: Class 'ZfcTwig\View\Strategy\TwigStrategy' not found in C:\wamp\www\ipci\module\ZfcTwig\src\ZfcTwig\Module.php on line 71. I looked for that missing file but everything seems to be in place.

class Module implements
    ServiceProviderInterface
{
    public function onBootstrap(MvcEvent $e)
    {
        $e->getApplication()->getServiceManager()->get('translator');
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getServiceConfig()
    {
        return include __DIR__ . '/config/services.config.php';
    }

}
# myproject/config/application.config.php
return array(
    'modules' => array(
        'Application',
        'DoctrineModule',
        'DoctrineMongoODMModule',
        'ZfcTwig',
        //'ReverseForm',
        //'ZendDeveloperTools',
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

View Helpers

I updated to the latest version of ZfcTwig, and I configured everything to work with namespaces.

But the viewhelpers I registered in the action controller are not found by twig. How do I need to register them?

Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'The function "dateLocalized" does not exist in "@common/index/index.twig" at line 43' in

This is how I do it now:

$renderer->getHelperPluginManager()->setInvokableClass(
    'dateLocalized', 'CommonBundle\Component\View\Helper\DateLocalized'
);

Enabling ZfcTwig Module causes all Custom View Helpers to return empty string '' lenght = 0

I have no idea why, but after enabling ZfcTwig in my project, all view helpers start to return string ''. Disabling it makes everything work again.

Something i noticed, is that the default zf2 view helpers are still working. For instance, url helper and menu helper are still generating menus and urls, but custom helpers return string ''. Maybe there is something overriding the custom helper logic, causing it to fail.

Replacing layout's blocks

the content of each .twig view file is putted in place of "content" var of layout.twig, but how can I fill the other blocks that are inside layout.twig?

i tried simply writing something like

layout.twig

{% block footer %}{% endblock %} # index.twig

{% block footer %}edited footer!{% endblock %}

but it doesn't work.
i also tried to write (without success):

index.twig

{% extends "layout/layout.twig" %}
{% block footer %}edited footer!{% endblock %}

Using built-in view helpers with settings

I'd like to use the built-in view helpers, but are running into problems. For instance, I want to do something like this:

$this->headMeta()->appendHttpEquiv(’expires’,
’Wed, 26 Feb 1997 08:21:57 GMT’);

I've tried {{ headMeta()->appendHttpEquiv(’expires’,
’Wed, 26 Feb 1997 08:21:57 GMT’)}}
and {{ this->headMeta()->appendHttpEquiv(’expires’,
’Wed, 26 Feb 1997 08:21:57 GMT’)}}

but both fail with the following message:
Twig_Error_Syntax
Unexpected token "operator" of value ">" in "layout/layout.twig" at line 6

Is there anything I can do to make this work?

using ZfcTwig brakes ViewJsonStrategy when registered at first

In my application, the ViewJsonStrategy is registered and used in "MyModule".

If i add "ZfcTwig" before "MyModule" in the application.config.php, the ViewJsonStrategy won't work:

  • if i use the "Accept: application/json" Header to "force" json rendering
  • and also if i return a JsonModel directly in my Controller/Action

If i add ZfcTwig after adding "MyModule", everything works fine.

application.config.php before - this will brake the ViewJsonStrategy:

<?php
return [
   'modules' => [
        'ZfcTwig',
        'MyModule',
    ],
];

this will fix the ViewJsonStrategy:

 <?php
 return [
    'modules' => [
         'MyModule',
         'ZfcTwig',
     ],
 ];

As far as i know, it happens because it's added at the same priority, so it is tested for the ability to render in the order it is added.

I think - at least - it's worth adding this to the Readme.md.

How can I register function, add a global etc?

$twig = ?
$twig->addExtension(new Twig_Extension_Debug());
$twig->addFunction('t', new Twig_Function_Function('Ext_View_TwigHelperSet::t'));
$twig->addGlobal('session', $_SESSION);
$twig->addGlobal('server', $_SERVER);
$twig->addFilter('indent', new Twig_Filter_Function('Ext_View_TwigHelperSet::indent'));
$twig->addFilter('unserialize', new Twig_Filter_Function('Ext_View_TwigHelperSet::unserialize'));

Can you help me?

zf2 layout variables

The layout engine in zf2 can be accessed from the controller as
$this->layout();

With php templates, one can just set a layout variable like $this->layout()->my_variable="test"

Why does this not work on twig templates ?

On the layout.twig file I have {{ my_variable }} and it does not render.

Add examples for disable_zf_model = true

I was a little confused how twig templates will work with the default zfctwig.disable_zf_model set to true. The example templates were actually written with in a way where that flag must be turned off.

It would be nice to update the examples to work out of the box with the default config or have examples for both modes.

formCollection not working

I wasnt able to get formCollection to work but i was able to use {{ formRow(form.get('username'))|raw }} but could this implemented?

{% do form.setAttribute('action', url('register')) %}
{% do form.prepare() %}
{{ form().openTag(form)|raw }}
{{ formCollection(form)|raw }}
{{ form().closeTag(form)|raw }}

Not found pages

When a page is not found (in the database) in my project I do the following in the action:

$this->getResponse()->setStatusCode(404);
return new ViewModel();

But the redirect tot the not found page is after rendering the twig view of the action where the not-found was 'thrown'.

Is this a ZF 'bug' or one of ZfcTwig and is there a way to redirect to the not-found page without rendering the view of the action?

Thanks

Problems with latest updates

I have just update to the latest version of ZfcTwig and i get a very ugly error: it seems that it can't load native php function like "is_object" in
{% if not is_object(game) %}

( ! ) Fatal error: Call to a member function compile() on a non-object in /Users/Oscar/Sites/Gamempire/svn/vendor/twig/twig/lib/Twig/Node/Expression/Function.php on line 31

I have tried to update the module.config with the new configuration array, but it still not works.

Problem using view helper in other view helper

Hi, I use a view helper in an other view helper called priceFormat dans I have an error.

This is the code of my view helper priceFormat : https://gist.github.com/91d14749cb799c08392f => module "Application"

In a the view helper ShowMovementDetail (module "Movement") I'm doing this
$this->getView()->priceFormat($value)
This line throw an exception : : Call to undefined method ZfcTwig\View\Renderer\TwigRenderer::priceFormat().

Have you gote an idea ?

Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException'

I was trying to call a controller in the layout by remplacing
{{ content | row }} with

{% render 'Article:Categorie:index'%} {% render 'Article:Article:index' %}

by hoping that it will have the same effect like on twig that is said
call of indexAction of Categorie controller of Article module and so on for the next

but i rather had
PHP Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Article' in C:\Program Files\Zend\Apache2\htdocs\GestionArticle\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:424

How can i resolve it please ?

partial view helper broken

Just updated using composer to the latest version and I am having tons of troubles:

Fatal error: Call to a member function getChildren() on a non-object in /vendor/zf-commons/zfc-twig/src/ZfcTwig/View/Renderer/TwigRenderer.php on line 191

ZfcTwig\Twig\Helper\Render error

ZfcTwig\Twig\Helper\Render has an error:

the use statement: use Zend\Mvc\View\InjectTemplateListener; needs to be changed to:
use Zend\Mvc\View\Http\InjectTemplateListener; as the Zend InjectTemplateListener is so named

Using viewhelpers in PhpRenderer when ZfcTwigRenderer is active

I'm having trouble using ZfcTwig in combination with normal Phprendering when using partials in my .phtml files, even while suffix_locked = true

When ZfcTwig is activated the inner partials will be rendered through Twig because the renderer inside the Zend\View\HelperPluginManager is being switched to ZfcTwig when the ViewRendererFactory is being called.

The layout that i am using is here

After some research i tracked it down to the ViewRendererFactory where the HelperPluginManager is being changed using setHelperPluginManager.

When the HelperPluginManager is being changed it will also attach the renderer to itself at this line and because the HelperPluginManager is being shared with the default phprenderer, any further calls to viewhelpers will now use the ZfcTwig renderer.

I'm not sure how to properly fix this without modifying ZF2

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.