如何在Symfony中访问基本模板文件中的模板变量

时间:2016-05-06 10:28:10

标签: symfony breadcrumbs

我的控制器操作

public function viewAction() {
        $breadcrumbs = array();
        $breadcrumbs = array("Home"=>$this->get("router")->generate("admin_home"));
$breadcrumbs = array("View"=>'');
       $this->render('UserBundle:Default:view.html.twig',array('breadcrumbs'=>$breadcrumbs));
}

这是我的View模板和" breadcrumbs"这里可以访问数组。

{% extends 'base.html.twig' %}
{% block body %}
<section class="content">
{{ dump(breadcrumbs) }}
</div>
{% endblock body %}

这是我的基本模板文件,但我无法在此处访问面包屑。

<!DOCTYPE html>
<html>
    <head>......
<section>
<div class="breadcrumb">
{{ dump(breadcrumbs) }}
</div>
</section>
{% block body %}{% endblock %}

注意: - 我不想使用任何捆绑包来获取面包屑。

2 个答案:

答案 0 :(得分:1)

您可以在base.html.twig中创建一个块:

<!DOCTYPE html>
<html>
    <head>......
<section>
<div class="breadcrumb">
{% block breadcrumb %}{% endblock %}
</div>
</section>
{% block body %}{% endblock %}

并将其填入 child 模板,就像body块一样:

{% extends 'base.html.twig' %}
{% block body %}
    <section class="content">
    (...) //content
    </div>
{% endblock body %}
{% block breadcrumb %}
    {{ dump(breadcrumbs) }}
{% endblock breadcrumb %}

修改 另外this可能对您有帮助,但我没有使用当前的Twig版本对其进行测试。

答案 1 :(得分:1)

您可以使用render(controller(...))

控制器:

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', [
            'breadcrumbs' => [
                'home' => 'home_url',
                'view' => 'view_url',
            ],
        ]);
    }

    public function breadcrumbsAction(array $breadcrumbs = []) {
        return $this->render('AppBundle::breadcrumbs.html.twig', [
            'breadcrumbs' => $breadcrumbs
        ]);
    }
}

base.html.twig

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}{% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    </head>
    <body>
        {{ render(controller('AppBundle:Default:breadcrumbs', { 'breadcrumbs': breadcrumbs })) }}
        {% block body %}{% endblock %}
        {% block javascripts %}{% endblock %}
    </body>
</html>

breadcrumbs.html.twig

{{ dump(breadcrumbs) }}

更新:使面包屑动态