Zend expressive - Layout

丶灬走出姿态 提交于 2020-01-16 18:25:13

问题


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:


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.



来源:https://stackoverflow.com/questions/47331032/zend-expressive-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!