How to get in template select-based field label instead of value?


#1

Hello.

I cannot find the way to get labels from select or multiselect or other value+label designed fields.

At example, I have field values like this:

en: English
fr: Francais

I need to print English instead of en in my template, but cannot find the way to get it. There is “Kirby Architect” plugin, may be this helps, but this only for Kirby 2.x. May be I missing to view some API function?

Thank you.


#2

You can use $page->blueprint() as a basis and then take it from there, see this cookbook recipe:
https://getkirby.com/docs/cookbook/templating/using-blueprints-in-frontend

E.g. to access a single field:

$field = $page->blueprint()->field('text');
echo $field['label'];

In the same way, you can get other properties of the field, like the options.


#3

Thanks for the hint, but I wonder how to grab the correct language in my template, e.g.:

  company:
    extends: fields/menuitems
    label: 
      de: Unternehmen
      en: Company

I thought
<?=$field->label()?> would be enough. I could not find in the docs how to access the language code/locale of a blueprint. Would love to receive you hint!

my dump() - Info:

Array
(
    [label] => Array
        (
            [de] => Unternehmen
            [en] => Company
        ) ...

Could be a Quicktip in the Cookbook :wink:


#4

You can get it from the array like this:

$field = $page->blueprint()->field('text');
echo $field['label']['de'];

I also corrected my code above, because $field is an array not an object, so to get the label, you have to use the index, not string syntax.


#5

Ok. I thought that I missed something when it comes to selecting the correct label depending on the locale.
So I have to take care for myself in blueprints, whereas having a extra field in the panel would automate my translation and take care automatically. Right?


#6

Sorry, I probably haven’t had enough coffee yet, but I’m not following you? Your use case seems to be different from that of @azmg?


#7

Sorry too, seems I am the one that had not enough coffee. I understood the question differently - maybe as I wanted to understand it my way. ;o)
My usecase is to print the correct label for the locale language in my template and the label is defined in blueprint.


#8

Yes, but the above code should then work for you, with the difference that instead of hardcoding the locale you would use the language code of the current language?


#9

Exactly - I thought to have missed something like a function or helper.
Now I finally go on with your advice:

<?= $field['label'][$kirby->languagecode()]

thanks you for your patience