Is there a way to define a default value for a snippet variable.
snippet('test', array('title' => 'my-title')); // with the variable
snippet('test'); // without the variable
I would like to define a default value in the snippet for that second case.
Inside the snippet, I tried this:
$title = = $_GET['title'] ?? 'Default title';
But this does not work.
$title = get('title') ?? 'Default title';
snippet('test', array('title' => $title));
Thanks for the super fast answer! It’s not working though.
$title = = get('title') ?? 'Default title'; is inside the snippet, the snippet will work with
snippet('test'); but the title passed with
snippet('test', array('title' => 'my-title')); does not show.
There shouldn’t be two “==”. And this code
$title = get('title') ?? 'Default title'; shouldn’t be inside the snippet if you want to pass it to the snippet…
Yes sure, that was a typo. It does not work either even with a single
Also, you are passing
'my-title to the snippet, instead of
Hmm, I think I was not clear so I will try to rephrase this:
I want to use a snippet in different places. Sometimes I want to pass variables to it, sometimes not. (It look like in my first post.)
If there is no variable, the snippet needs to work anyway. (Actually it does not even need a default value: if the variable is here, the snippet does something with it, if not, it does not)
Oh, it’s probably too late or too early.
Ok, then in the snippet, then try this to check if title is set, otherwise use some other value:
$title = $title ?? 'Some other value';
Cool! that works. thank you very much.
A follow up question: is there a way to do the opposite?
- if the snippet has no variable, use a default value
- if the snippet receive a falsy value
('title' => false), don’t use the default value, and pass this falsy value to the snippet.
Hm, the snippet shouldn’t actually output the default value if
$title is false. Isset returns false only if
$title doesn’t exist or is NULL.