Twig 包含动态数据 [英] Twig include with dynamic data

查看:29
本文介绍了Twig 包含动态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Slim Framework 和 Twig 编写一个网站.

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.

我已经浏览了 twig 文档,除了包含函数/标签之外,我没有看到任何有用的东西,但我不知道如何轻松获取数据.

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?

推荐答案

在阅读 Anticoms 答案后,我能够通过编写 Twig 扩展来实现.

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);
}

现在我可以简单地写

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

进入我的树枝模板以使用我想要的数据呈现模板.

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

请注意,我的 render() 函数在运行时使用了瘦依赖注入来实例化控制器.

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

这篇关于Twig 包含动态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆