smarty-php / smarty

Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic.
Other
2.26k stars 712 forks source link

how to use loadFilter() ? #1045

Closed KarelWintersky closed 4 months ago

KarelWintersky commented 4 months ago

https://www.smarty.net/docs/en/api.load.filter.tpl

But:

$smarty->loadFilter(Smarty::FILTER_OUTPUT, "htmlentities");

throws:

SmartyException: outputfilter 'htmlentities' not found or callable

$smarty->registerPlugin(Smarty::PLUGIN_FUNCTION, 'htmlentities', 'htmlentities');
$smarty->loadFilter(Smarty::FILTER_OUTPUT, "htmlentities");

Produces same result for all and any plugin type.

P.S. I need auto escape of string variables, like:

<textarea>{$history|htmlentities}</textarea>

without unnecessary calls, since there are a lot of output fields and unnecessary calls clutter the code.

KarelWintersky commented 4 months ago

Upd: Alone

$smarty->registerFilter(Smarty::FILTER_OUTPUT, "htmlentities");

produces:

1/1 TypeError

htmlentities(): Argument #2 ($flags) must be of type int, Smarty_Internal_Template given

in ..../vendor/smarty/smarty/libs/sysplugins/smarty_internal_runtime_filterhandler.php on line 63

But

$smarty->registerFilter(Smarty::FILTER_OUTPUT, "htmlentities");
$smarty->loadFilter(Smarty::FILTER_OUTPUT, "htmlentities");

produces same result:

1/1 SmartyException

outputfilter 'htmlentities' not found or callable

in ..../vendor/smarty/smarty/libs/sysplugins/smarty_internal_method_loadfilter.php on line 61

Also, https://www.smarty.net/docs/en/advanced.features.outputfilters.tpl return 500 server error.

KarelWintersky commented 4 months ago

Solved via:

$smarty->setEscapeHtml(true); 
// or
$smarty->escape_html = true

but...

wisskid commented 4 months ago

You found the answer! You cannot load a filter using a unregistered function, which is what caused the first error. But for your usecase auto-escape is better anyway.

KarelWintersky commented 4 months ago

What about other output filters? For example, function that translates output to other language?

How to use it?

How to register function and use it for output filter?

wisskid commented 4 months ago

Please see the Smarty 5 documentation on this topic when using Smarty 5: https://smarty-php.github.io/smarty/5.x/api/filters/output-filters/