Zend expressive - Layout

2019-08-20 09:31发布

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 :)

1条回答
唯我独甜
2楼-- · 2019-08-20 10:19

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.

查看更多
登录 后发表回答