ddoddsr's avatar

use blade-like text substitution in method

I would like to substitute text like blade does with a text stored in the database.

A row is selected which copies it to the text field where it may be edited before final use.

Example Row: Hello {{ name }}, how are you today? {{agent_name}}

Text substitution would take place in the copy method so the text would become:

Result in text field: Hello John, how are you today? Bob

What function or package is available for this? What is the proper name for this kind of action?

0 likes
4 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The process you're describing is often referred to as "template rendering" or "string interpolation." In Laravel, Blade is the templating engine that handles this kind of text substitution. However, if you want to perform similar text substitution outside of Blade, you can use PHP's str_replace or preg_replace functions, or even a more sophisticated templating library.

Here's a simple example using PHP's str_replace to achieve this:

function substituteText($template, $variables) {
    foreach ($variables as $key => $value) {
        $template = str_replace('{{ ' . $key . ' }}', $value, $template);
    }
    return $template;
}

$template = "Hello {{ name }}, how are you today? {{ agent_name }}";
$variables = [
    'name' => 'John',
    'agent_name' => 'Bob'
];

$result = substituteText($template, $variables);
echo $result; // Outputs: Hello John, how are you today? Bob

In this example, the substituteText function takes a template string and an associative array of variables. It replaces each placeholder in the template with the corresponding value from the array.

If you need more advanced templating features, you might consider using a library like Twig or Plates, which are more powerful and flexible than simple string replacement. However, for basic use cases, the above approach should suffice.

ddoddsr's avatar

@LaryAI is there a LAravel or Filament function for "template rendering" or "string interpolation."

Niush's avatar

@ddoddsr If the text is not directly controlled by the user, you can use blade's render function.

\Illuminate\Support\Facades\Blade::render(
  'Hello {{ $name }}, how are you today? {{ $agent_name }}',
  [
    'name' => 'John',
    'agent_name' => 'Bob'
  ],
  deleteCachedView: true
);

https://laravel.com/docs/11.x/blade#rendering-inline-blade-templates


Alternatively, you can use Laravel's string swap function:

str('Hello {{name}}, how are you today? {{agent_name}}')->swap([
  '{{name}}' => 'John',
  '{{agent_name}}' => 'Bob'
])->toString();

Obviously with this approach spaces between curly braces matter. i.e. {{ name}} won't swap.

ddoddsr's avatar

Hi used a variation of the function suggested by the bot

Please or to participate in this conversation.