Twig include with dynamic data

落爺英雄遲暮 提交于 2019-12-12 02:34:09

问题


I'm writing a website using Slim Framework and Twig.

The sidebar on the website will have dynamically created links and i want to get the links from the database/cache every time a page is rendered, i can do this in each controller action but i would like to do this in my base template so i don't have to get and render the data manually in every controller action.

I have looked through the twig documentation and I haven't seen anything that could be of use besides the include function/tag but i don't see how i could get the data easily.

Is my only option to write an twig extension to do this or is there an easier way?


回答1:


First of all: templates usually shouldn't contain any type of bussines logic but only render the data you provide it. However you could write a custom twig function and use that to aquire the menu data from the DB in order to render it in your base template. Alternativeley you could write some Slim middleware that aquires the data which might be able to inject the data into the template.

Hope that helps.




回答2:


After reading Anticoms answer i was able to do it by writing a Twig extension.

public function getFunctions()
{
    return array(
        new \Twig_SimpleFunction('render', array($this, 'render'))
    );
}

public function render($template, $controller, $action) {
    $app = Slim::getInstance();
    return $app->$controller->$action($template);
}

Now i can simply write

{{ render('Shared/sidebar.twig', 'Controller', 'Index') }}

Into my twig template to render the template with the data i want.

Note that my render() function uses slim dependency injection to instanciate the controller at runtime.



来源:https://stackoverflow.com/questions/30030830/twig-include-with-dynamic-data

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