Search code examples
modx

Use page variables in Snippet (ModX, 1.0.5)


(Using ModX 1.0.5)

When I execute my current snippet (see snippet below), it seems to completely ignore the if(empty()) checks. I have also tried with if($promoX == ''), also no luck.

<?php
    $promo1 = '[*sidepromotop*]'; // assets/images/promo1.jpg
    $promo2 = '[*sidepromobot*]'; // this variable is empty.

    if(empty($promo1) && empty($promo2)){
       echo '[!Ditto? &startID=`92` &depth=`1` &display=`2` &randomize=`1` &tpl=`Promo-Block-Styles`!]';
    }else{
       if(empty($promo1)){
          echo '[!Ditto? &startID=`92` &depth=`1` &display=`1` &randomize=`1` &tpl=`Promo-Block-Styles`!]';
       }else{
          echo '<div class="promo"><img src="'.$promo1.'" alt="" /></div>';
       }
       if(empty($promo2)){
          echo '[!Ditto? &startID=`92` &depth=`1` &display=`1` &randomize=`1` &tpl=`Promo-Block-Styles`!]';
       }else{
          echo '<div class="promo"><img src="'.$promo2.'" alt="" /></div>';
       }
    }
?>

The code above will for some reason display the following:

<div class="promo">
    <img src="assets/images/promo1.jpg" alt="">
</div>
<div class="promo">
    <img src="" alt="">
</div>

As you can see, even if the variable is empty, it apparently still treats it as not empty when I run it though my code.

I would really appreciate some insight on this, as I am very new to modx, and it is giving me such a headache!

Thanks!


Solution

  • MODX tags such as [*sidepromotop*] are not parsed from within a snippet (it's raw php), so in fact the empty() checks are working perfectly as you are passing them the unparsed tag as a string.

    What you need to do instead is make use of $modx->getTemplateVar() for retrieving the current document's template variables:

    $promo1 = $modx->getTemplateVar('sidepromotop');
    

    Alternatively, you can pass them as parameters into your snippet call...

    [!mySnippet? &promo1=`[*sidepromotop*]` &promo2=`[*sidepromobot*]`!]
    

    ...and they will be available as the variables $promo1 and $promo2 in your snippet code.

    *

    You should also use $modx->runSnippet() to execute Ditto from within the snippet, it will be much more efficient.

    $output = $modx->runSnippet('Ditto', array(
        'startID'   => 92,
        'depth'     => 1,
        'display'   => 1, 
        'randomize' => 1,
        'tpl'       => 'Promo-Block-Styles',
    ));
    return $output;
    

    Check out this wiki article for some great tips for creating snippets for MODX: http://wiki.modxcms.com/index.php/Creating_Snippets