简体   繁体   中英

Zend expressive - Layout

In my layout (Twig), i'd like to retrieve a value from a Middleware authentication .

If i put, in templates.global.pĥp:

'twig' => [
        'globals' => [
            // Variables to pass to all twig templates
            'auth' => (new \Zend\Authentication\AuthenticationService())->hasIdentity(),
        ],
    ],

And in layout default.html.twig

{% if auth %}
    Connect
{% else %}
    Not connect
{% endif %}

This code works, but, is it a good method ?

Thank you :)

It's not a good method. First of all, using the config files to set global template data is meant for static data. Creating a service in the config will fail if you want to cache the config. I don't know about the zend auction service, but it would be better to get it from the service manager or any other container you are using. This way you make sure that everywhere in your application the same service is being used.

For common variables or services which are needed in templates, I have a wrapper around the TemplateRenderer . So instead of calling the original template renderer, I call my own class and in there I populate the template with common data.

And you can also inject default parameters with TemplateRendererInterface::addDefaultParam . In any other middleware you can inject the templaterenderer, set the desired default data and later on access it in your templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM