Smarty registerClass() call with named (like PHP 8+) arguments
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) }
?
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
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: "","" , ")"
Smarty does not support named arguments (yet). Might be a useful improvement.
It will be very useful :smile_cat:
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'
