Calling different snippets depending on category selection

Hello!

I want a user to be able to select between two different options for a splash screen.
The template:

<?php snippet('header') ?>

<?php if($page->category() == 'A')  
{  echo " <?php snippet('A') ?> "; } 
   else { echo " <?php snippet('B') ?> "; } 
?>

<?php snippet('footer') ?>

And here’s the simplified blueprint:

title: Home
fields:
  category:
    label: Splash
    type: radio
    default: B
    options:
      B: B
      A: A

I’m trying to do what’s being discussed in this thread, trying to “include a different snippet depending on page settings” as @texnixe suggests, but think I am implementing it wrong…

Any help would be appreciated :slightly_smiling:

Your code outputs the literal strings of PHP codes. What you need is this:

<?php snippet('header') ?>

<?php
if($page->category() == 'A') { 
  snippet('A');
} else {
  snippet('B');
}
?>

<?php snippet('footer') ?>
3 Likes

I knew I was doing something very basic wrong - thank you for your help!

What about …

<?php snippet($page->category()); ?>

… which seems kind of more future proof to me, if an option ‘C’ will be added one time or radio will become a select. ‘B’ is set as default, so nothing unexpected should happen.

One issue that could come up is when an unexpected snippet is selected. This could be a security issue even.

I agree that this could be an issue, if the text file is edited outside of the panel. You could, however, build in a security check to make sure that only a snippet which is in the allowed options can be selected.

Thank you for this.

Would the original answer not be subject to this security problem?
If I implemented the future proof but riskier answer, how would you build a security check?

yes. the ‘else’-clause of the original answert would expose the same risk. just add if and else if statements.

to solve it all in code you could use dynamic options via json.
https://getkirby.com/docs/cheatsheet/panel-fields/select

and parse the same file when selecting the snippet to check if the value is correct.
you could also add a md5/sha1 value of the original json file to the code to make sure it has not been altered.
http://php.net/manual/en/function.sha1-file.php