在laravel中使用多个翻译文件时出现htmlspecialchars错误

时间:2019-03-02 18:54:54

标签: php laravel laravel-blade

我目前正在为我的laravel项目进行翻译。一切正常,但仅当我只使用一个翻译文件时。

我试图使事情井井有条,为此,我想到了为侧面组件(登录/注销链接,后退按钮,类似的东西)准备一个翻译文件,然后介绍其他翻译文件的想法进行更具体的操作,例如翻译在个人资料的仪表板上找到的组件。

例如,这是我的英文翻译文件:

general.php     

return [
    "login" => "Login",
    "register" => "Register",
    "logout" => "Logout",
    "back" => "Back",
    "postBy" => "Posted by",
    "name" => "Name",
    "email" => "E-Mail Address",
    "pass" => "Password",
    "confirmPass" => "Confirm Password",
    "rememberMe" => "Remember Me", 
    "forgotPass" => "Forgot Your Password?",
];

dashboard.php

<?php

return [
    "title" => "Your Messages",
    "header" => "Message",
    "create" => "Add Message",
    "edit" => "Edit",
    "delete" => "Delete",
];

执行此操作已经出现错误,甚至没有在我的 dashboard.blade.php 文件中使用它。我得到的错误是:

  

ErrorException(E_ERROR)htmlspecialchars()期望参数1为   字符串,给定的数组(查看:   C:\ xampp \ htdocs \ messageboard \ resources \ views \ layouts \ app.blade.php)   (视图:   C:\ xampp \ htdocs \ messageboard \ resources \ views \ layouts \ app.blade.php)

虽然我什至没有尝试用{{ __('dashboard.title') }}之类的名称来调用它。我不知道是什么原因导致这个错误。

根据要求,这是导致错误的视图。无论加载什么页面,我都会遇到相同的错误,因此我假设它将是这个视图,因为它基本上已经包含在其他所有视图中并在其他视图中进行了扩展。

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    <i class="far fa-envelope"></i>
                    {{ config('app.name', 'Messageboard') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('login') }}">{{ __('general.login') }}</a>
                            </li>
                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('general.register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="/dashboard">{{ __('Dashboard') }}</a>
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('general.logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <div class="container">
            <main class="py-4">
                @include('inc.statusmessages')
                @yield('content')
            </main>
        </div>    
    </div>
</body>
</html>

控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Message;
use App\User;
use Auth;

class MessagesController extends Controller
{

    public function __construct(){
        $this->middleware('auth', [
            'except' => [
                'index',
                'show'
            ]
        ]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $messages = Message::orderBy('created_at', 'desc')->get();
        return view('messages')->with('messages', $messages);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createmessage');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'body' => 'required|min:15|max:500'
        ]);


        // Create Message
        $message = new Message;
        $message->title = $request->input('title');
        $message->body = $request->input('body');
        $message->status = 100;
        $message->user_id = auth()->user()->id;

        $message->save();

        return redirect('/dashboard')->with('success', 'Message Created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $message = Message::findOrFail($id);       
        $user = User::findOrFail($message->user_id); 

        $messageData = [
            'message' => $message,
            'user' => $user
        ];

        return view('showmessage')->with($messageData);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $userId = 0;
        $message = Message::findOrFail($id);

        if (Auth::check())
        {
            // The user is logged in...
            $userId = Auth::user()->id;
        }

        if((int)$userId !== (int)$message->user_id) {
            return "Poster ID: ".$message->user_id.", User ID: ".$userId;
        }

        return view('editmessage')->with('message', $message);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required',
            'body' => 'required|min:15|max:500'
        ]);

        $message = Message::find($id);
        $message->title = $request->input('title');
        $message->body = $request->input('body');
        $message->status = 100;
        $message->user_id = auth()->user()->id;

        $message->save();

        return redirect('/dashboard')->with('success', 'Message Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $message = Message::find($id);
        $message->delete();

        return redirect('/dashboard')->with('success', 'Message Removed');
    }
}

任何帮助将不胜感激。我希望我已经足够清楚,否则请告诉我。

1 个答案:

答案 0 :(得分:1)

正如@Magnus Eriksson所指出的,这是因为您在刀片视图中使用了{{ __('Dashboard') }},而有一个dashboard.php翻译文件。

__()翻译助手通常会退回到没有匹配翻译键的情况下返回的字符串,但是在这种情况下,它确实找到了翻译文件。由于您未使用文件中的特定键,例如dashboard.title,因此它将从文件中返回完整的转换数组,然后在呈现刀片视图时将其提供给htmlentities()