如何在laravel-blade模板中检索php代码中的翻译字符串



我试图在laravel 8中的blade模板中使用php foreach循环代码内部字符串的本地化检索。

在foreach循环中,我试图操作一个名为$item['label']的值,并使用laravel所具有的语言本地化来等效翻译它的值。

这是我当前的代码。

@foreach ($items as $item)
@php
$item['label'] = "{{ __($item['label']) }}"
@endphp
@endforeach

但我收到的错误

ParseError语法错误,意外的"(T_ENCAPSED_AND_WHITESPACE(,应为"-"或标识符(T_STRING(或变量(T_variable(或数字(T_NUM_STRING(

首先,我可以在@php中使用{{ __ ('string') }}@lang('string')吗?如果我做不到,还有其他方法吗?

非常感谢!

@php和@endphp是一个blade语法,它与编写相同

<?php ?>

所以你可以这样做:

<?php  
echo __('profile/username'); 
?>

或者您可以使用Blade模板引擎编写:

@php
echo __('profile/username'); 
@endphp

要打印项目,您可以这样做:

@foreach ($items as $key => $item)         
{{  __($item) }}
@endforeach

这里有一个数据示例:

@php 
$items = ['engine_1' => ['label' => 'Google'], 'engine_2' => ['label' => 'Bing']];
@endphp
@foreach ($items as $key => $item)         
{{  __($item['label']) }}
@endforeach
// The output will be => Google Bing

为了保存项目的翻译;{{}}";并使用密钥来检测在哪个索引上应用更改,如下所示:

@foreach ($items as $key => $item)
@php     
$items[$key]['label'] =  __($item['label'])
@endphp
@endforeach

注意@Nurbek Boymurodov给你写的内容,你需要使用$key,因为这样做不会覆盖foreach循环中的数据:

@foreach ($items as $key => $item)
@php
$item['label'] =  __($item['label']); // Wrong way of overriding data
@endphp
@endforeach

在使用foreach时,您不能在此处更改其值。如果$items是数组而不是stdClass ,请尝试此操作

@foreach ($items as $key => $item)
@php
$items[$key]['label'] = __($item['label']);
@endphp
@endforeach

谢谢,@Nurbek Boymurodov!

正是你的评论回答了我的问题。

这是现在的代码:

@foreach ($items as $item)
@php
$item['label'] = __($item['label']);
@endphp
//other codes where I used the manipulated $item['label']
@endforeach

通过删除{{ }},我已经操纵了我想要的值,谢谢!

最新更新