Laravel Blade - 允许用户输入变量

Laravel Blade - User Allowed to Input Variable

我正在使用来自 thetispro/laravel5-setting 的存储包为我的 laravel 5.2 应用程序创建一个管理设置部分。

我希望我的管理员用户能够更新发送给用户的电子邮件副本,但有些电子邮件包含用户名等变量。 "Thanks for shopping with us, CUSTOMER NAME".

我可以轻松地将以下内容存储在设置中,但是当 blade 输出它时,它只是将其打印为字符串而不是变量。我试过使用 {{}} 和 {{!! !!}。这是我拥有的:

管理员用户可以编辑的电子邮件:

<h2>Hi, {{ $user->name }}</h2>
<p>Welcome to my web app</p>

在我看来我有:

{!! Setting::get('emailuserinvite') !!}
<br /><br />
<!-- Testing both escaped and nonescaped versions -->
{{ Setting::get('emailuserinvite') }}

blade 呈现的只是:

echo "<h2>Hi, {{ $user->name }}</h2>
<p>Welcome to my web app</p>";

我试图制作一个自定义的 blade 指令,它可以关闭回显、显示变量并打开回显备份,但这似乎也无法正常工作。

// AppServiceProvider
Blade::directive('echobreak', function ($expression) {
  // echo "my string " . $var . " close string";
  $var = $expression;
  return "' . $var . '";
});

// Admin user settings
Hi @echobreak($user->name)
Welcome to my web app

如有任何建议,我们将不胜感激!谢谢。

更新

我使用@abdou-tahiri 的示例模拟了一个简单的测试用例,但我仍然遇到 eval() 代码的错误。

ErrorException in SettingController.php(26) : eval()'d code line 1:   Undefined variable: user

这是我的简单控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Blade;

class SettingController extends Controller
{

    public function index() {
        $user = [
            "fname" => "Sam",
            "lname" => "yerkes"];
        $str = '{{ $user }}';
        return $this->bladeCompile($str, $user);
    }

    private function bladeCompile($value, array $args = [])
    {
        $generated = \Blade::compileString($value);
        ob_start() and extract($args, EXTR_SKIP);
        try {
            eval('?>'.$generated);
        } 
        catch (\Exception $e) {
            ob_get_clean(); throw $e;
        }
        $content = ob_get_clean();
        return $content;
    }

}
<h2>Hi, $user->name</h2>
<p>Welcome to my web app</p>

这是你想要做的吗?

<h2>Hi, {{$user->name}}</h2>
<p>Welcome to my web app</p>

您可能需要使用 Blade 编译字符串,检查这个辅助函数:

function blade_compile($value, array $args = array())
{
    $generated = \Blade::compileString($value);

    ob_start() and extract($args, EXTR_SKIP);

    // We'll include the view contents for parsing within a catcher
    // so we can avoid any WSOD errors. If an exception occurs we
    // will throw it out to the exception handler.
    try
    {
        eval('?>'.$generated);
    }

    // If we caught an exception, we'll silently flush the output
    // buffer so that no partially rendered views get thrown out
    // to the client and confuse the user with junk.
    catch (\Exception $e)
    {
        ob_get_clean(); throw $e;
    }

    $content = ob_get_clean();

    return $content;
}

因此在您的视图文件中:

{!! blade_compile(Setting::get('emailuserinvite'),compact('user')) !!}

勾选这个Is there any way to compile a blade template from a string?