Detect if in a loop or not

Kind of an odd question, but is there a way to know if your inside a loop or not, and more importantly what the variable is for that loop? Im working on my Carver plugin, and im making a tag that needs to work as if it was a loop. So in php that would be something like:

<?php foreach($pages->visible() as $sitepages): ?>
  <!-- stuff in here -->
<?php endforeach ?>

I need a way to know the context the tag is working in. Currently they only work in a page context.

I want to be able to do this:

<kb:pages src="blog" mode="children">
  <kb:title field="title" wraptag="h1" />
  <kb:kt field="text" />
</kb:pages>

But for that to work, the title, and kt tags need to know they should be getting the info from the loop fetched from pages tag, which should contain all the children of the current page (i want to support siblings etc as well). So tag needs to work off $sitepages rather then $page or whatever the as has been set to.

How can i switch between a loop of stuff, or the page? I really hope that made sense. I would like to support the builder plugin too, which uses $data in the blocks.

Short answer: you can’t.

Hrmm… that wasn’t the answer i was hoping for, but it is the one i feared :frowning: I’m sure there is a way as i’ve seen it done. Off to google then…

5 hours later… I think im going to have write my own core thats Kirby aware. I think im hitting a wall since its using open source library that is general purpose. Still, ill learn a thing or too in the process. I got what I wanted on a basic level using variable variables:

<?php

$src = 'site';
$mode = 'children';
$status = 'listed';

$context = ${$src};

$dataset = $context->{$mode}()->{$status}();

foreach ($dataset as $dataitem) {
  echo $dataitem->title();
}

?>

But doing it inside the custom tags, i’m hitting walls since the tag parser isn’t closely tied in enough to Kirby. Oh well…

you could use a templating language like mustache or handlebars in content and use a custom field method to inject the page object. but i guess that defeats the custom language you are intending to use.

The point is that i’ve tried most of those, and blade too, but the idea is to make as close to using html as possible to make it easier for designers to make templates.

I laid awake for hours last night trying to wrap my head around the problem. i think i can still use the custom tag approach, but lean on snippets rather then a bespoke tag library. So basically it will be supercharged snippets that can be combined to get what you need, and there will still be a library of them.