We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 49324
    • 14 Posts
    Hello, supposing i have this snippet that contains various functions

    if (!function_exists('test')) {
      function test() {
            return "test";
      }
    }
    if (!function_exists('test_one')) {
      function test_one() {
            return "test one";
      }
    }


    and i add this [[!snippet]] inside my template.

    How can i then call one of those 2 functions in various parts of the template? Thanks
      • 28042 ☆ A M B ☆
      • 24,524 Posts
      You should just be able to call the function in another snippet. Loading the snippet at the beginning of your template makes its functions available within MODX.
      <?php
      $output = test();
      return $output;


      Keep in mind that if you use any MODX values or API functions inside of your functions you have to declare global $modx to allow the function to access the $modx object.
        Studying MODX in the desert - http://sottwell.com
        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
        Join the Slack Community - http://modx.org
        • 49324
        • 14 Posts
        Thanks sottwell, but that way i should create a snippet for each function i want to call. Is it possible instead to create a single snippet that can dynamically call each function based on a placeholder or by passing it a parameter?
          • 29661
          • 116 Posts
          You can use call_user_func function, so it will look like:

          <?php
          $fn = $modx->getOption('fn', $scriptProperties, '');
          if (empty($fn)) {
              return 'No function was specified.';
          }
          
          call_user_func($fn);
          


          and you should be able to call the snippet like
          [[yourSnippet? &fn=`functionName`]]
          
            --
            John
            @theboxer