【问题标题】:Laravel htmlspecialchars() expects parameter 1 to be string, array givenLaravel htmlspecialchars() 期望参数 1 是字符串,给定数组
【发布时间】:2018-02-22 22:23:18
【问题描述】:

我尝试在我的配置文件夹中获取languages.php 提供的语言列表,但出现此错误

htmlspecialchars() expects parameter 1 to be string, array given (View: C:\laragon\www\newproject\resources\views\layouts\panel.blade.php) (View: C:\laragon\www\newproject\resources\views\layouts\panel.blade.php)

这是我的languages.php

<?php

return [
  'en' => [
      'name' => 'English',
      'flag' => 'images/flags/en.png'
  ],
  'fa' => [
      'name' => 'پارسی',
      'flag' => 'images/flags/iran.png'
  ],

];

我的中间件Language.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;


class Language
{
    public function handle($request, Closure $next)
    {
      if (Session::has('applocale') AND array_key_exists(Session::get('applocale'), Config::get('languages'))) {
          App::setLocale(Session::get('applocale'));
      }
      else { // This is optional as Laravel will automatically set the fallback language if there is none specified
          App::setLocale(Config::get('app.fallback_locale'));
      }
      return $next($request);
    }
}

LanguageController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;

class LanguageController extends Controller
{
    public function index($lang)
    {
      if (array_key_exists($lang, Config::get('languages'))) {
            Session::put('applocale', $lang);
        }
        return Redirect::back();
    }
}

路线

Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@index']);

最后是我的观点

<li class="dropdown langs">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
  {{ Config::get('languages') }} <span class="caret"></span>
</a>

 <ul class="dropdown-menu" role="menu">
   @foreach (Config::get('languages') as $lang => $language)
   @if ($lang != App::getLocale())
   <li>
     <a href="{{ route('lang.switch', $lang) }}">{{ $language['name'] }}</a>
   </li>
   @endif
   @endforeach
 </ul>
</li>

【问题讨论】:

  • 问题在 'layouts\panel.blade.php' ,请分享这个文件。
  • @sunitiyadav 我在问题中的最后一部分代码是我的 panel.blade.php

标签: php laravel laravel-5


【解决方案1】:

错误出现在下拉定义的{{ Config::get('languages') }} 这一行,在这里您希望打印一个字符串,而不是尝试像字符串一样打印取自 languages.php 的完整数组,因此htmlspecialchars 函数失败,因为第一个参数与所需的参数类型不匹配。

【讨论】:

  • 好的,我明白了,但我需要在顶部显示所选语言,我该怎么做?
  • @mafortis {{ Config::get('languages')[App::getLocale()]['name'] }} 将是一个选择,您的应用始终有一个语言环境,您可以使用区域设置作为键访问配置语言。
猜你喜欢
  • 2018-11-10
  • 2017-08-08
  • 2017-03-22
  • 2017-07-12
  • 1970-01-01
  • 2017-08-30
  • 2018-07-30
  • 2018-08-04
  • 1970-01-01
相关资源
最近更新 更多