How to use $pages and $site inside a function

linke in this tiny expl.

function foo(){
echo $pages->find("test/test")->title();
}

You’ll probably want to use title instead of titel. Otherwise it looks like it could work. Where do you have this function? What are you trying to do?

$pages is not defined within foo()… to pass it foo($pages) does not work too
to serialize is also not possible

This should work:

function foo($pages){
return $pages->find("blog/extending-kirby")->title();
}

echo foo($pages);

However, within your function you should make sure that the page exists before trying to call a method.

Thanks @texnixe this works. But my real case is a bit more complex… what if I have to use $pages inside foo like this…

<?php function foo($X, $pages){ ?>

<?php foreach($pages->find($X->t1(), $X->t2(), $X->t3()) as $T): ?>
<a href="<?= $T->url() ?>">
<article>
<h1 class=“bold”><?= $T->title(); ?></h1>
<p><?= $T->teaser_text(); ?></p>
</article>
</a>
<?php endforeach ?>

<?php } ?>

What is this supposed to do? This is not valid code, what are all the php tags doing inside there?

Also, your function would have to return or at least echo something. If you want to write HTML, use a snippet, not a function.

I ried to avoid having two snippets with almost the the content. $X can be a child or a grand child. Anyway tank you for your help.

You can pass variables to a snippet, allowing you to use the same snippet with different page collections while at the same time avoiding to return HTML from a function.

2 Likes