We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 20993
    • 37 Posts
    Hello-

    I have TV that is setup for an image. What I want to do is write a conditional statement that checks to see if an image path is present and if it is it displays the image, but if not it doesn’t display anything.

    I am not a PHP developer, so I basically made up this code and put it in a snippet called CondImage, although I know it is wrong:


    <?php
    $image = [*sidebarimage*] 
    
    if $image == "" {
    } else {
    <img src="[*sidebarimage*]" alt="" />
    }
    ?>


    Then I would just call the snippet [[CondImage?]] from within my template. Any help straightening me out would be appreciated.

    Thanks

      • 4310
      • 2,310 Posts
      One way I’ve used is have a TV for your image link say named "ImageLink"
      Create your snippet:
      if( $TVarray = $modx->getTemplateVarOutput(array(ImageLink)) ){ $tvOutput = $TVarray[ImageLink];
      if(empty($tvOutput)) return '';
      else return ''.$tvOutput.''; };

      Assign the the TV to your template, add the tag [*ImageLink*] wherever you want the image to appear.
      Add the call to your new snippet in the template.
      If you add a path to an image in the "ImageLink" TV it should appear, if the TV is empty then nothing will.
      EDIT - changed to a snippet
        • 20993
        • 37 Posts
        Thanks for the help! but, I haven’t gotten it to work yet.

        I have a TV for the image path called: [*sidebarimage*]

        Then I created a snippet and added your code to it called: [[CondImage]]

        then in my template I have something like:

        <div class="navbottom" >[[CondImage]]<img src="[*sidebarimage*]" alt="" border="0" /></div>


        Can you help/explain to me what I did wrong here.

        Thanks

          • 4310
          • 2,310 Posts
          Sorry for the confusion the snippet looks for content in the TV.
          If you have
          <img src="path-to.jpg" alt="" border="0" />

          in the TV and
          <div class="navbottom" >[[CondImage]]</div>
          in the template/page then if there is a path it will display the image.
          If not then the <div> would be empty.
            • 20993
            • 37 Posts
            Yep, that did it. Thanks a ton smiley
              • 4310
              • 2,310 Posts
              Glad you got it working.