How can I use HTML tags in a Laravel localization file?
Asked Answered
H

3

79

I'm trying to utilize Laravel's localization feature, but I need to be able to put emphasis or bolden a portion of a phrase. Inserting a HTML tag into the language file causes it to be escaped when outputted to a blade.

For example, here is my language file entry:

return [
    'nav' => [
        'find' => '<strong>Find</strong> Your Home',
    ]
];

When I call it from within a blade: (I've tried using triple braces as well.)

{{ trans('base.nav.find') }}

It outputs:

&lt;strong&gt;Find&lt;/strong&gt; Your Home

I could potentially split the phrasing up like:

return [
    'nav' => [
        'fyh' => [
            'find' => 'Find',
            'yh'   => 'Your Home',
        ]
    ]
]

And then output:

<strong>{{ trans('base.nav.fyh.find') }}</strong>{{ trans('base.nav.fyh.yh') }}

But that seems like overkill. Any better solutions?

Holusbolus answered 12/6, 2015 at 19:26 Comment(1)
The second option isn't just overkill, it's broken. What's a translator supposed to do if in their language the verb goes at the end of the sentence? You can place translated strings close to each other on a page, but you generally don't want to concatenate them to form sentences or paragraphs.Bloodstone
F
167

Use {!! !!} instead of {{ }} to prevent escaping:

{!! trans('nav.find') !!}
Forthright answered 12/6, 2015 at 19:27 Comment(4)
Ahh, damn! I'm not sure how I overlooked that. Thank you. I will accept the answer when SO allows me to.Holusbolus
@MichaelIrigoyen You mentioned triple braces, so I just wanted to mention that his is one of the changes between L4 and L5. In L4, {{ }} was unescaped and {{{ }}} was escaped. In L5, {!! !!} is unescaped and {{ }} is escaped.Autoionization
Thanks, my last stint with Laravel was version 4, so I missed that change now that I'm working with a clean install of 5.1Holusbolus
Be aware that the unescaped approach can lead to vulnerabilites like XSS if the attacker can somehow write to /langRadiography
D
11

Using @lang directive:

@lang('nav.find')

Source: Retrieving Translation Strings

Diaeresis answered 4/3, 2019 at 10:31 Comment(1)
This @lang directive is not helping with span markup when used for 'placeholder'Overnight
S
8

Using Laravel 5.6 and above, can use the __ helper along with the blade syntax:

{!! __('pagination.next') !!}

Had to do those for the pagination blade templates.

Sable answered 12/9, 2018 at 20:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.