Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Add function "str_replace" to Volt

Hi,

I'm trying to add the PHP function "str_replace" to Volt.

The following code doesn't work and I don't understand why

services.php

$compiler = $volt->getCompiler();
$compiler->addFunction(
  'str_replace',
  function($resolvedArgs, $exprArgs) use ($compiler)
  {
    $firstArgument = $compiler->expression($exprArgs[0]['expr']);
    $secondArgument = $compiler->expression($exprArgs[1]['expr']);
    $thirdArgument = $compiler->expression($exprArgs[2]['expr']);
    return 'str_replace("'.$firstArgument.'", "'.$secondArgument.'", "'.$thirdArgument.'")';
  }
);

test.volt

{{ str_replace("Harris", "Sheldon", "My name is Harris.") }}

Could you help me?

Thank you.



55.1k
Accepted
answer

You can simply specify a string as second argument, which will look for it in the global namespace:

$compiler->addFunction('str_replace','str_replace');


1.3k

Thank you Lajos Bencz, it works.