Laravel 5在动态字段上嵌套花括号

时间:2018-06-14 05:56:38

标签: php laravel laravel-5 nested laravel-blade

我想在控制器上创建动态字段并将变量传递给刀片。 我有像这样的控制器

public function create()
{
   $AdditionalField=AdditionalFieldController::generateHTML(1);
   return view("addcontact")->with(['AdditionalField'=$AdditionalField]);
}

print_r($AdditionalField)的输出是:

<div class="col-lg-1 col-md-12 col-sm-12 text-right">
    <label class="text-gray-dark"  for="address_2">address_2</label>
</div>
<div class="col-lg-3 col-md-8 col-sm-12">
     <input class="form-control " id="address_2" value="{{isset($editContact['address_2'])?$editContact['address_2']:''}}"  name="address_2">
</div>

在我的刀片上,我将此代码用于显示字段。

 {!!  $AdditionalField !!}

输出

mypic

但我想在刀片上告诉我这个

mypic

更新

  public static function generateHTML($moduleId)
{       
   $AdditionalFieldKeys = AdditionalFieldKey::where("module_id", $moduleId)->get();
    $html = '';
    foreach ($AdditionalFieldKeys as $additionalFieldKey) {
        $type = AdditionalFieldController::getInputType($additionalFieldKey->additional_field_key_name);
        $fieldName = AdditionalFieldController::getInputName($additionalFieldKey->additional_field_key_name);
        $file = AdditionalFieldController::getTemplate($type);
        $variable = AdditionalFieldController::getVariables($fieldName,$this->model_name);
        $html .= AdditionalFieldController::fillTemplate($variable, $file);
    }
    return $html;
}
    public static function getTemplate($type)
{
    $file = base_path('modules/AdditionalField/view/' . $type . '.stub');
    return file_get_contents($file);
}

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,你需要使用类似StringBladeCompiler的内容。

要安装此组件,您必须执行两个步骤(也在StringBladeCompiler的自述文件中记录):

  1. 在项目目录中运行composer require "wpb/string-blade-compiler"
  2. config/app.php中将Illuminate\View\ViewServiceProvider::class行替换为Wpb\String_Blade_Compiler\ViewServiceProvider::class,如下所示:

    //Illuminate\View\ViewServiceProvider::class,
    Wpb\String_Blade_Compiler\ViewServiceProvider::class,
    
  3. 之后,您可以使用基于字符串的模板。因此,在您的控制器中,您必须使用两个view来电。最后它看起来像那样:

    public function create()
    {
        $AdditionalField=AdditionalFieldController::generateHTML(1);
        $editContact['address_2']='ali';
    
        return view("addcontact")->with([
            'AdditionalField'=>view(['template' => $AdditionalField])->with(['editContact' => $editContact])
        ]);
    }
    

    如果您必须向“内部”视图提供任何变量,您可以像外部视图调用一样添加with

    另一个解决方案是重构你的方法而不是生成字符串模板,但使用“包含”之类的东西。