Looping Templates in foreach() only returns final template

#44 · open · 2 comments

View on GitHub ↗

ThomasDeer

I'm trying to allow ordering of which templates get shown through a foreach loop, (essentially i'm building a slider thats generated through lots of template parts being pulled together, very specific use case but it has standard slides built into the plugin, then these will be overwritable within the theme) however my foreach loop is only returning the final item ` foreach ($orderArr as $template_slug) { $my_template_loader->set_template_data( $userData )->get_template_part( $template_slug ); }` My orderArr is `Array ( [0] => welcome [1] => slide1 [2] => slide2 )` However if i manually call the template parts `$my_template_loader->set_template_data( $userData )->get_template_part( 'welcome' ); $my_template_loader->set_template_data( $userData )->get_template_part( 'slide1' ); $my_template_loader->set_template_data( $userData )->get_template_part( 'slide2' );` It all works as expected. Any suggestions would be helpful

Comments

GaryJones

Interesting. I would have assumed that your `foreach` would have worked correctly. Totally untested, but would using the [yield keyword](https://www.php.net/manual/en/language.generators.syntax.php) work here? ```php $orderArr = [ 'welcome', 'slide1', 'slide2' ]; foreach ( $orderArr as $template_slug ) { yield $my_template_loader->set_template_data( $userData )->get_template_part( $template_slug ); } ```

ThomasDeer

Just given this (yield) a go and appears to have the same behaviour, if I echo the template name after the get_template_part (in my original code) `$my_template_loader->set_template_data( $userData )->get_template_part( $template_slug ); echo $template_slug; ` The page renders with welcome slide1 (slide 2 complete content) slide2,