Performance-wise, is it better to call a snippet inside a loop or vice-versa?


#1

Stricly performance-wise, is it more efficient to call a snippet inside a loop, or is it better to place said loop inside the snippet?

In other words, when creating a blog, which is the better method:

This:

blog.php

<?php foreach ($articles as $article) {
  snippet('blogarticle', ['article' => $article])
} ?>

blogarticle.php

<h2><?= $article->title()->html() ?></h2>

Or this:

blog.php

<?php snippet('blogarticles', ['articles' => $articles]) ?>

blogarticles.php

<?php foreach ($articles as $article) {
  <h2><?= $article->title()->html() ?></h2>
  // whatever
} ?>

#2

I think its better to decide first if you really need the snippet. Are you going to use that snippet in more then one template? If not, then don’t bother with the snippet, unless its going to end up being a huge amount of code.

This won’t work either…

<?php foreach ($articles as $article) {
  <h2><?= $article->title()->html() ?></h2>
  // whatever
} ?>

Should have been:

<?php foreach($articles as $article): ?>
  <h2><?= $article->title()->html() ?></h2>
<?php endforeach ?>

#3

I’d go for the first. I don’t know about performance, but from a coding style point of view. Otherwise, 2 days later you don’t know what your snippet call does. Keep the logic where it belongs.

A snippet for just a headline is unnecessary.

In my opinion it makes sense to use snippets even if they are only used in one template. That way you can create components with their own styles and maybe reuse in other projects.


#4

Thank you for your answer.

The code I provided was just an illustration, it’s obviously absurd to call a snippet for a single line of code; adding more code for this precise example would have been unnecessary.


#5

Sure, I guessed as much but for the benefit of people reading this who are very new to Kirby and PHP, it may not have looked incorrect to them, so i tidied up the last bit for that reason :slight_smile:


#6

Another reason why the logic in the snippet doesn’t make sense - and here we talk about performance again - is that the call to the snippet may be completely unnecessary in case there are no articles to loop through.