Laravel中如何在PHP括号内的字符串中插入HTML代码或换行?
解决Laravel翻译字符串中插入HTML换行无效的问题
核心原因
Blade的{{ }}语法会自动转义所有HTML内容,直接插入的<br>会被解析成实体字符<br>,无法渲染为换行效果。
可行解决方案
1. 改用非转义输出语法
将{{ }}替换为{!! !!},该语法不会转义HTML标签,能直接解析<br>:
{!! __('this word on top<br/>this word will be below') !!}
也可以拆分翻译项后拼接:
{!! __('this word on top') . '<br/>' . __('this word will be below') !!} > 注意:仅当翻译内容为可信静态内容时使用此方法,若包含用户输入的动态内容,会存在XSS攻击风险。
2. 在语言文件中定义带换行的翻译项
在resources/lang目录对应的语言文件(如zh-CN/messages.php)中直接定义包含<br>的翻译字段:
return [ 'line_break_content' => 'this word on top<br/>this word will be below', ];
然后在模板中用非转义语法调用:
{!! __('messages.line_break_content') !!}
3. 用换行符配合nl2br函数
如果不想直接写HTML标签,可在字符串中使用\n换行,再通过nl2br转换为<br>,最后用非转义输出:
{!! nl2br(__('this word on top\nthis word will be below')) !!}
也可以在语言文件中定义带\n的字段,再用同样方式调用。
4. 用模板结构实现换行
如果不需要HTML标签,直接通过模板结构拆分内容:
<p>{{ __('this word on top') }}</p> <p>{{ __('this word will be below') }}</p>
或者通过CSS样式实现纯文本换行:
<div style="white-space: pre-line;">{{ __('this word on top\nthis word will be below') }}</div>
内容的提问来源于stack exchange,提问作者ART
相关产品推荐
相关产品推荐

