0

How to add line break in laravel language files? I have tried to use
,
, \n\r, to break line and add new line but all these not work.

return [
     'best_hospitality' => 'Simply <br /> the best hospitality',
 ];
vicky793
  • 431
  • 1
  • 3
  • 17
  • 2
    Does this answer your question? [Break lines in blade translation files](https://stackoverflow.com/questions/37727515/break-lines-in-blade-translation-files) – Digvijay May 22 '20 at 06:59
  • @Digvijay No sir. that tags work only on balde template. not for message.php file – vicky793 May 22 '20 at 07:04

3 Answers3

0

You can use

'best_hospitality' => "<pre>Simply\r\nthe best hospitality</pre>",

or 'best_hospitality' => sprintf ('<pre>Simply%sthe best hospitality</pre>',PHP_EOL ),

please note the use of double quotes in the first example, it is not working with single quotes if you use the \r\n inside the string, this is why

if you try echo(Lang::get('message.best_hospitality')) you will see the new line:

I am not so sure if you need the pre tag, depends where you need to use the Lang for html or not, eg using (double quotes here):

'best_hospitality' => "Simply\r\nthe best hospitality",

and var_dump(Lang::get('message.best_hospitality')); exit;

has the output

C:\wamp64\www\test\app\Http\Controllers\TestController.php:24:string 'Simply
the best hospitality' (length=39)

Does this cover your case?

0

You need HTML Entity Names on your lang files. Try this :

return [
     'best_hospitality' => 'Simply &lt;br&gt; the best hospitality',
 ];
STA
  • 30,729
  • 8
  • 45
  • 59
0

May I suggest creating a custom helper function for this specific case?

Add this into your helpers.php file:

if (! function_exists('trans_multiline')) {
    /**
     * Retrieve an escaped translated multiline string with <br> instead of newline characters.
     */
    function trans_multiline($key, array $replace = [], string $locale = null): string
    {
        return nl2br(e(__($key, $replace, $locale)));
    }
}

Now you will have a function trans_multiline() available for you in any view, which will behave pretty much like the built-in __() helper.

The function will fetch a localized string of text and replace any newline \r\n symbol with <br> tag.

Caveat: For a proper escaping it must be done before nl2br() function, like you see in the code above. So, to prevent any weird errors due to double-escaping, you must use this custom helper without any additional escaping, like so:

{!! trans_multiline('misc.warning', ['name' => 'Joe']) !!}

Escaping will be handled by the e() function (which is what Laravel uses under the hood of {{ }}) inside the helper itself.

And here's how you define a multiline translation string:

'warning' => "There's only 1 apple, :name!\r\nDon't eat it!"

Make sure to use double-quotes, so PHP actually replaces \r\n with a newline character.

Obviously, parameter replacing still works exactly like with the __() helper.