Passing variable to snippet not working

I’m trying to passing a css class to a snippet with the following code:
<?php snippet('optin', array('class' => 'optin--post' )); ?>

and the snippet looks like this:
<div class="optin <?php echo $class } ?>">

But I’m getting a ‘Undefined Variable: class’ error through through the debug mode;

I also tried this:
<div class="optin <?php if($class->isNotEmpty()) { echo $class; } ?>">

But no luck, how can I make this work?

The code in your first snippet is not correct, there is an extra curly brace.

The method isNotEmpty() (in your second snippet) can only be used on an instance of the field class, not on an arbitrary variable.

You can test if the variable has been set like this:

<div class="optin <?php echo isset($class)? $class: '';  ?>"></div>
1 Like

How do I add a class when fetching this default snippet?

<?php snippet('coverimage', $article) ?>

Also, what just having the $article does as opposed to having array('article' => something) ?

As far as I know, the snippet() method expects an array as second argument. The advantage is, that you can easily pass multiple variables to the snippet template like this …

<?php snippet('coverImage', array('article' => $article, 'class' => 'myclass')); ?>

Now you can use $article and $class in your snippet template.

1 Like

You have already asked this question above, that’s why I’ve moved it here :wink:

You can pass just the variable, if you pass a page object which does not require an additional value (as done in the Starterkit).

<?php snippet('coverimage', $page) ?>

You can also use the following syntax to pass an array of key/value pairs:

<?php snippet('prevnext', ['flip' => true]) ?>
4 Likes