php - Condition inside variables -
i have example works great:
$text = 'lorem ipsum'; $html = <<<html <div> <span>$text</span> </div> html;
now how right way 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;
i think work template engine - don`t worry, pretty easy use.
only thing need prepared project composer , after install 1 of template engine (for example picked latté).
install of composer:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php composer-setup.php
after installing latté:
php composer.phar require latte/latte
and on end, can create this:
$latte = new \latte\engine; $latte->settempdirectory('/path/to/tempdir'); $parameters['val'] = 2; $html = $latte->rendertostring('template.latte', $parameters);
and put content file "template.latte" in same directory:
<select> {foreach [1, 2, 3] $key} <option {if $val === $key}>option {$key}</option> {/foreach} </select>
this solution used professionals many reasons:
- put logic , rendering side side, not mixed things up.
- all variables automatically escaped (to avoid xss)
- dry (do not repeat yourself) principe, row option should written once
btw should use triple equals in condition in php (compares type of variable). more safe , can save lot of time of debug using principle :-).
Comments
Post a Comment