hi!
as far as i understand, the ->content()
function loops over all fields as long as they are not a structured / nested type of field.
how would you go to make it work also for structured fields?
so far i have two ideas:
- use kirby blueprint reader to read the field
type
in the blueprint (if there’s one), and add the necessary code to loop over it; all in all it feels too limited, it needs a blueprint to check against, and you need to make sure to check all fields type names (eg plugin name) that produce structured fields.
- use a regex against the value of the structured field, split the string in substrings by using
"
as delimiter, and reconstruct the structured fields; this does not need to check against a blueprint, but in my case (extending the spad plugin), this option leaves me with half of the data i need to include in the json tree structure, as i don’t have access to the name of the structured subfields.
any idea? maybe just hacking together a generic (deep) recursive function?
Maybe you could just manually build up a nested array? if you consistently name all the strutcure fields, it shouldn’t be to hard.
You briefly touched on json, but whats your actual desired result? whats the use case? There are other plugins for outputting JSON like this one, and it looks like it handles structured fields.
My intent is to extend the spad plugin to be able to include in the json tree structure kirby built-in structured fields as well as for example kirby builder…
I came across that other kirby plugin, but I’d like to extend spad as it feels a way ligther and simpler plugin compared to kirby-json-api. All in all a slightly different approach, which I prefer amongst the two options.
Will keep playing for a while and see what to do!
You can add a simple check, here’s a basic outline you can. probably build upon:
<?php
foreach($page->content()->data() as $key => $value) {
if(substr( $value, 0, 1 ) == '-') { // pretty basic, you could extend this with another regex, in case other fields start with a dash
foreach($page->$key()->toStructure() as $item) { // this will then loop through all fields. of the structure
foreach($item as $key => $value) {
echo $item->$key();
};
}
} else {
echo $page->$key();
}
}
?>
Or check how they do it in the plugin James mentioned above, looks like it uses a regex pattern you could test.
1 Like
yep thank you!
somehow in the right direction then
A bit unorthodox, but might be an approach as well:
<?php
foreach($page->content()->data() as $key => $value) {
foreach($page->$key()->toStructure() as $item) {
if(is_a($item, 'Field')) {
echo $page->$key().'<br>';
}
if(is_a($item, 'Structure')) {
foreach($item as $key => $value) {
echo $item->$key().'<br>';
}
}
}
}