Reuse snippets in kirby

My project grows every day, so I decide to put repeating content in a reusable snippet and call the snippet in place:

<?php if($image = $data->image()): ?>
	<img src="<?php echo thumb($image, array(
			'width' => 480,
			'quality' => 1
		))->url(); ?>"
		data-src="<?php echo $image->url() ?>"
		alt="<?php echo $site->title()->html(); ?> – <?php echo html($data->image()->caption()) ?>"
		class="lazyload blur-up" />
<?php endif ?>

than I call the snippet in a another snippet:

<?php snippet('image') ?>

But I got an error: Undefined variable: data

How do I send variables with a snippet?
There is an section here: https://getkirby.com/docs/templates/snippets but I did not get it to work :frowning:

snippet('nameofsnippet', $variable, false/true);

the last parameter will “echo” or render the content and print it like it is, such as for in emails…

@carstengrimm

<?php snippet('image', $data; true) ?>

Not sure what is wrong, but this gives the following error:

syntax error, unexpected ';', expecting ',' or ')'

you use $data; instead $data,

(simicolon is wrong)

<?php snippet('image', $data) ?>
<?php snippet('image', $data) ?>

did you define your variable $data somewhere? you can’t call a variable if it’s not available

Then you probably have to use the long version:

<?php snippet('image', array('data' => $data)) ?>

provided that the variable used in the snippet, that references the snippet, is called $data.

1 Like

@carstengrimm @texnixe

The long form did the trick!

It is possible to hand over more than one $variable?

BTW: since you have already defined $image, you can then use this variable throughout in your snippet:

<?php echo html($image->caption()) ?>
1 Like

Yes,

<?php snippet('image', array('data' => $data, 'someothervariable' => $someothervariable)) ?>

Edit: you can also use another variable name in the snippet, for example:

<?php snippet('image', array('something' => $someother)) ?>
2 Likes

Thanks, this is awesome! :slight_smile: