pug-php / pug

Pug template engine for PHP
https://www.phug-lang.com
MIT License
391 stars 42 forks source link

Ternary Operator Issue #119

Closed Riant closed 7 years ago

Riant commented 7 years ago

Mixin:

mixin avatar_img(default_src)
  - var _default_src = default_src || 'default-xxx.png'
  img(src=$userinfo['user_thumb'] ? $userinfo['user_thumb'] : _default_src)

When I call the mixin with +avatar_img('abc') or +avatar_img(), I got the error like below:

Use of undefined constant _default_src - assumed '_default_src' (View: xxx\xxxx\index.pug)

It looks like did not support the ternary operator like a ? b : (c ? d : 'xxx') or a ? b : ( c || 'xxx').

Thanks.

kylekatarnls commented 7 years ago

Hi,

You should not mix JS and PHP in expressions. The following will work with default settings:

mixin avatar_img(default_src)
  - $default_src || ($default_src = 'default-xxx.png')
  img(src=$userinfo['user_thumb'] ? $userinfo['user_thumb'] : $default_src)

To get full JS syntax every where, you need the expressionLanguage option set to 'js':

use Pug\Pug;

$pug = new Pug(array(
  'expressionLanguage' => 'js',
));

But this will not properly handle the JS || because in JS || returns any kind of value, in PHP it returns only booleans.

So be aware var _default_src = default_src || 'default-xxx.png' is exactly the same in JS as a ternary: var _default_src = default_src ? default_src : 'default-xxx.png' In PHP not, you have to use ternary: $_default_src = $default_src ? $default_src : 'default-xxx.png'

Riant commented 7 years ago

O, Got it, Thanks.

kylekatarnls commented 7 years ago

With pug-php 3, ternary expressions can now be used inline. Hope you will enjoy the new version.