0

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.

2 Answers 2

3

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']) }}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.