【问题标题】:How to retrieve translation strings inside a php code in laravel blade template如何在 laravel 刀片模板中的 php 代码中检索翻译字符串
【发布时间】:2021-03-14 06:39:43
【问题描述】:

我正在尝试在 laravel 8 的刀片模板中使用 php foreach 循环代码中字符串的本地化检索。

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

这是我当前的代码。

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

但我得到一个错误

解析错误 语法错误,意外的 '' (T_ENCAPSED_AND_WHITESPACE),需要 '-' 或标识符 (T_STRING) 或变量 (T_VARIABLE) 或数字 (T_NUM_STRING)

首先,我可以在@php 中使用{{ __ ('string') }}@lang('string') 吗? 如果我不能,还有其他方法可以解决这个问题吗?

非常感谢!

【问题讨论】:

  • 不要在@php中使用双括号你不需要使用它

标签: laravel laravel-8 laravel-localization


【解决方案1】:

@php 和@endphp 是刀片语法,和写法一样:

<?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

【讨论】:

    【解决方案2】:

    谢谢,@Nurbek Boymurodov!

    是您的评论回答了我的问题。

    下面是代码:

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

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

    【讨论】:

    • 快乐编码,别忘了给我的正确答案
    【解决方案3】:

    在使用 foreach 时,您无法在此处更改其值,如果 $items 是数组而不是 stdClass,这将起作用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2021-10-13
      • 2017-08-20
      • 2015-08-04
      • 2017-04-03
      相关资源
      最近更新 更多