duancaozen6066 2016-07-25 22:10
浏览 27

变量内部条件

I have this example which works great:

$text = 'Lorem Ipsum';

$html = <<<HTML
<div>
   <span>$text</span>
</div>
HTML;

Now how to do this the right way to get option 2 selected:

$val = 2;

$html = <<<HTML
<select>
   <option if ($val == 1) {echo 'selected';} >Option 1</option>
   <option if ($val == 2) {echo 'selected';} >Option 2</option>
   <option if ($val == 3) {echo 'selected';} >Option 3</option>
</select>
HTML;
  • 写回答

2条回答 默认 最新

  • drktvjp713333 2016-07-25 22:37
    关注

    I think this is the work for template engine - but don`t worry, is pretty easy to use.

    Only thing you need is prepared project with composer and after that easily install one of the template engine (for this example I picked up Latté).

    Install of composer:

    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php composer-setup.php
    

    after that installing Latté:

    php composer.phar require latte/latte
    

    And on the end, you can create something like this:

    $latte = new \Latte\Engine;
    
    $latte->setTempDirectory('/path/to/tempdir');
    
    $parameters['val'] = 2;
    
    $html = $latte->renderToString('template.latte', $parameters);
    

    and put this content into file "template.latte" in same directory:

    <select>
    {foreach [1, 2, 3] as $key}
        <option {if $val === $key}>Option {$key}</option>
    {/foreach}
    </select>
    

    This solution is used by professionals for many reasons:

    1. put logic and rendering side by side, does not mixed things up.
    2. All variables are automatically escaped (to avoid XSS)
    3. DRY (Do not Repeat Yourself) principe, that row with option should be written only once

    BTW you always should use triple equals in condition in PHP (compares also type of variable). Its much more safe and you can save a lot of time of debug using this principle :-).

    评论

报告相同问题?