I tried the structure field example
fields:
addresses:
label: Addresses
type: structure
entry: >
{{street}}<br />
{{zip}} {{city}}
fields:
street:
label: Street
type: text
zip:
label: ZIP
type: text
city:
label: City
type: text
But I can’t figure out how I can access this in my template.
I tried it with:
<?php foreach($addresses as $address): ?>
<div class="address">
<?php echo $address['Street'] ?><br />
<?php echo $address['ZIP'] ?> <?php echo $address['City'] ?>
</div>
<?php endforeach ?>
But it don’t work
Keep in mind that I am totally new to php!
1 Like
I’m rather new to Kirby as well and had the same problem. Here’s how I figured it out, but I’m not sure if this is the best way…
You have to parse the field as yaml first, than foreach through every item. Then you access the fields using the bracket syntax $item['field']
. Here’s an example with a structure I used to create a slideshow.
<?php $slides = yaml($page->slider()); ?>
<?php foreach($slides as $slide): ?>
<li class="mastheadSlider_slide">
<img
class="mastheadSlider_image"
src="<?php echo $page->image($slide["image"])->url()?>"
alt="Bible" />
<div class="mastheadSlider_info">
<h1><?php echo $slide["title"]; ?></h1>
<p><?php echo $slide["text"]; ?></p>
</div>
</li>
<?php endforeach; ?>
2 Likes
That’s actually the way to go. Kirby does not automatically convert YAML fields as they are just like any other field for the Kirby core (only the Panel knows about the structure field). The yaml()
helper is Kirby’s helper to convert the field back to a PHP data structure.
By the way, using the new Kirby syntax you can also write:
<?php $slides = $page->slider()->yaml(); ?>
1 Like
Thanks for the answer!
I tried it like this:
<?php $addresses = yaml($page->slider()); ?>
<?php foreach($addresses as $address): ?>
<?php echo $address["street"];?>
<?php endforeach; ?>
But it still not show anything at all
Should probably be “addresses” not “slider”?
<?php $addresses = $page->addresses()->yaml(); ?>
2 Likes
Oh… yeah… Thats it. I am stupid Thank you!
Is there a way to put this in a function or something? That its more easily accessible?
As I said, I am a total coding newbie, so maybe thats a stupid question
You can either use a controller if the code you want to outsource is specific to the presentation (template) or a model if you only want to extract the YAML conversion part - or a combination thereof.
This example should be added to docs:
Access structure fields from templates:
<?php $addresses = $page->addresses()->yaml(); ?>
<?php foreach($addresses as $address): ?>
<?php echo $address["street"];?>
<?php endforeach; ?>
It’s already there http://getkirby.com/docs/cheatsheet/field-methods/yaml; but you are right, we should link from the structure field to the yaml()
and structure()
methods. I’ll put than on the to do list, if it’s not in a pull request yet.
Thanks for your input
Edit: I just added the links to the docs.
1 Like