Reputation: 2793
tl; dr: I am looking for something like "template_from_string" in Twig.
Long version (including use case):
I have a string like "Hello |NAME_OF_RECIPIENT| lorem ipsum ... more stuff.. more dynamic data..." and I am looking for a nice way to replace |NAME_OF_RECIPIENT| with dynamic data using Blade's feature set like directives and variables etc. I found Blade's compileString method which returns the compiled php script, nice, but I want the string with replacements (i.e. "Hello Peter").
Laravel version is 5.1.
Upvotes: 0
Views: 792
Reputation: 4821
In your language files:
return [
"message" => "Hello :name, you are :age years old!",
];
From your blade template:
@lang('message', [
'name' => 'Peter',
'age' => 23,
])
Will display:
"Hello Peter, you are 23 years old!"
Laravel will automatically replace :name
with the supplied name, and age
with the supplied age. You can do this for any amount of variables.
You can read more about it in the Laravel localization docs, but I can't find any mention of the @lang
function for some reason.
Upvotes: 1
Reputation: 733
Laravel offers a localization service. You could use this service to achieve what you want and if you decide to go multilingual with your app in the future, you can do this painless. Take a look at the localization documentation.
You can pass data to a language string with like they did in the "Replacing Parameters In Language Lines" section. Then you use trans helper function to display it on the Blade.
{{ trans('welcome', ['name' => 'Peter']) }}
Upvotes: 3