Passing a KibryTag attribute into a field query

Hello,

I currently have a KirbyTag that allows me to insert a snippet that takes the values from a structured YAML field, and converts its data into a table. Until now, my project has only needed one such table per page, so I hard coded in the specific field name (distances) into my KirbyTag plugin. However, I now need the ability to pass the name of a different field to this plugin (but default to distances if no value is provided).

Here’s my tag:

(distances: title: Optional title)

I’m envisaging the following being possible:

(distances: more_distances title: More distances)

Here is my current plugin:

return [
    'attr' => [
        'title'
    ],
    'html' => function ($tag) {
        return snippet('scope/distances', [
            'title' => $tag->title(),
            'distances' => $tag->parent()->distances()->yaml()
        ], true);
    }
];

So, I need a way of being able to modify $tag->parent()->distances()->yaml() where the distances() part of the query can be replaced by the tags value.

TL;DR: I need to pass a KibryTag attribute into a field query. Is this possible?

I cannot currently test it but I assume the following would work:

return [
    'attr' => [
        'title'
    ],
    'html' => function ($tag) {
        $fieldname = empty($tag->value) ? 'distances' : $tag->value;

        return snippet('scope/distances', [
            'title' => $tag->title(),
            'distances' => $tag->parent()->content()->get($fieldname)->yaml()
        ], true);
    }
];

[edit] an empty tag attribute being empty and not null, I’ve edited the $fieldname = ... line.

That works, thanks! Out of interest, why does the query need to go via content()?

It doesn’t have to, I wrote it like this only because I find it more readable (although a little longer), but both lines would work:

$tag->parent()->$fieldname()->yaml();
$tag->parent()->content()->get($fieldname)->yaml();
1 Like