Symfony Twig 扩展渲染视图

Symfony Twig extension render view

我的twig扩展代码如下

/**
 * @return array
 */
public function getFunctions()
{
    return [
        new \Twig_SimpleFunction('bsPanelTitle', array($this, 'bsPanelTitle')),
    ];
}


/**
 * @param $headline
 * @return string
 */
public function bsPanelTitle($headline)
{
    $loader = new \Twig_Loader_Filesystem(__DIR__ . '/../Resources/views/Common/Placeholder');
    $twig = new \Twig_Environment($loader);
    return $twig->render('xtitle.html.twig', ['headline' => $headline]);
}

我的问题是:

是否有更好的方法从 Twig 扩展功能到达 AppBundle/Resources/views/Common/Placeholder 文件夹?

如评论中所述,使用 include() 将模板包含在您需要的任何地方。

例如,以下与您要实现的目标相同:

app/Resources/views/xtitle.html.twig:

{% stylesheets '@AppBundle/Resources/css/bootstrap.css' %}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

{# Other Markup Here #}

在您的模板中,只需调用:

{% include 'xtitle.html.twig' %}

这将包括模板以及 bootstrap 样式和该模板中的任何其他内容。

因为这个问题是用 symfony2 标记的,我假设你确实在谈论 symfony2 项目,如果是这种情况,你可以使用 twig 配置注册你自己的命名空间,像这样:

twig:
    # ...
    paths:
        "%kernel.root_dir%/../pathFromProjectRootToPlaceholder/Placeholder": placeholder

这会为文件夹 pathFromProjectRootToPlaceholder/Placeholder 创建一个别名,然后您可以使用它来呈现您的模板,如下所示:

//from controller
return $this->render(
    '@placeholder/index.html.twig',
    $data
);

{# from twig template #}
{% include '@placeholder/index.html.twig' %}

您可以向同一个别名添加多个路径,但有关更多信息,请查看 symfony 2 站点上的官方说明书: http://symfony.com/doc/current/cookbook/templating/namespaced_paths.html

希望这对您有所帮助,

亚历山德鲁·科索伊