smarty icon indicating copy to clipboard operation
smarty copied to clipboard

Smarty registerClass() call with named (like PHP 8+) arguments

Open KarelWintersky opened this issue 2 years ago • 6 comments

We can register class:

$smarty->registerClass("OptionSwitcher", "\My\App\OptionSwitcher");

and use it something like this:

{OptionSwitcher::html('switch_debug_mode', 'is_debug_mode_active') }

It works nice... but OptionSwitcher::html() method have more than two arguments:

public static function html(string $switcher_id = '', string $exposed_smarty_variable = '', string $on_text = 'YES', string $off_text = 'NO', string $css_tuning_class = '', string $request_uri = '', bool $is_enabled = true): string
    {
// ... 
}

If it is necessary to pass a different value for the is_enabled argument than the default value, you will need to list all the arguments preceding it, passing the desired values (or default values):

{OptionSwitcher::html('switch_debug_mode', 'is_debug_mode_active', 'YES', 'NO', '', '', false) }

... looks ugly

The way out of this is the named argument mechanism introduced in PHP 8: https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments

array_fill(start_index: 0, count: 100, value: 50);

or, in my case:

// call
OptionSwitcher::html('switch_debug_mode', 'is_debug_mode_active', is_enabled: false)

Does Smart support such a mechanism at the templates? Like this:

{OptionSwitcher::html('switch_debug_mode', 'is_debug_mode_active', is_enabled: false) }

?

KarelWintersky avatar Feb 28 '23 15:02 KarelWintersky

Looks like NOT in version 3.4.2:

Fatal error: Type of SmartyCompilerException::$line must be int (as in class Exception) in /path/to/vendor/smarty/smarty/libs/sysplugins/smartycompilerexception.php on line 8

KarelWintersky avatar Feb 28 '23 17:02 KarelWintersky

in version 4.3.0:

Syntax error in template "file:options.tpl" on line 161 "{OptionSwitcher::html('switch_districts_visible', 'is_districts_visible', is_enabled: false)}" - Unexpected ": ", expected one of: "","" , ")"

KarelWintersky avatar Feb 28 '23 18:02 KarelWintersky

Smarty does not support named arguments (yet). Might be a useful improvement.

wisskid avatar Feb 28 '23 21:02 wisskid

It will be very useful :smile_cat:

KarelWintersky avatar Mar 01 '23 08:03 KarelWintersky

For example, in my case:

{OptionSwitcher::html('switch_debug_mode', 'is_debug_mode_active', css_tuning_class: 'red-blue-switcher', request_uri: '/fo/bar') }

passed args string $on_text = 'YES', string $off_text = 'NO'

KarelWintersky avatar Mar 01 '23 08:03 KarelWintersky

image image

KarelWintersky avatar Mar 01 '23 08:03 KarelWintersky