简体   繁体   中英

Using subsections of an array in Twig as if they were the main

If I have an array passed to twig like this

$values = [
  'title'=>'Title of Page',
  'subsection_a'=>[
                   'title'=>'Title of Subsection'
                  ],
];

What I'd want to do is for a specific section in my template, use 'subsection_a' as the base so when I do {{ title }} it says "Title of Subsection" rather than "Title of Page"

I'm very unfamiliar with Twig, and I'm testing it as a replacement for a template engine I threw together for a project.

If your dividing the main proportion of your templates in subtemplate you can do it with the keyword with :

controller.php

echo $twig->render('main.twig, [
    'title' => 'parent',
    'foo'   => 'bar',
    'bar'   => 'foo',
    'child' => [
        'title' => 'Child',
        'foo'   => 'Foobar',
    ]
]); 

main.twig

<h1>{{ title }}</h1>
<p>{{ foo }}</p>

{% include "child.twig" with child %}

child.twig

<h2>{{ title }}</h2>
<p>{{ foo }}</p>

twigfiddle

There is no Twig-way of achieving this. If it's just for ease of use, you could set a short variable, such as

{% set sub = subsection_a %}

This would allow you to write {{ sub.title }}.

You could create a new array with twig, merge the specific subsection, but in your case, it would make managing the code more difficult, you could have duplicate and it might not be worth the trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM