如何在Laravel的if-else子句中包含不同的刀片模板视图?

时间:2014-09-16 15:31:13

标签: php laravel blade

我经历了Laravel Blade tutorial。我在我的项目中使用它。但我想根据下拉列表中选择的项目添加不同的刀片模板视图。

示例: - 我有一个创建Question.blade.php页面。

Question.blade.php

<div class="question_type">
<?php $question_type= array('--' => '--- Select Question Type ---') 
+QuestionType::lists('name', 'id') ?>
{{ Form::select('question_type', $question_type,'--' ,array('id'=>'question_type','class' => 'form-control')) }}
</div>

现在我想根据在Question_Type下拉列表中选择的选项添加不同类型的视图。我试图用Java Script做到这一点。

Java脚本代码: -

 function addQuestion() 
 {
   var question_type=$("#question_type").val();

   switch (question_type) 
   {
    case 1:
    $("#Questions").load("questions/type1.blade.php");
    case 2:
    $("#Questions").load("questions/type2.blade.php");
    default:
    $("#Questions").load("questions/default_type.blade.php");
  }
} 

但我收到错误 localhost / mywebsite / question / questions / type1.blade.php 404(未找到)

是否有任何解决方案可以使用@if @else或@switch根据下拉列表选择项目的值来包含刀片视图?

我的伪代码: -

@if {{question_type.selected.val='1'}}
@include(question.type1);
@elseif {{question_type.selected.val='2'}}
@include(question.type2);
@else
@include(question.default_type);
@endif

1 个答案:

答案 0 :(得分:1)

如果你要求laravel,你需要有一个与route相关联的方法(无论是在他们的hello world示例中的简单闭包还是在{{3}中的方法})。)。

内部,方法是您可以在哪个视图上返回的逻辑:

if($someCondition) {
    return View::make('template1');
} else {
    return View::make('template2');
}

在您的javascript中,将您的question_type作为参数发送到AJAX请求中。然后在您的控制器方法中,您可以做出决定:

$("#Questions").load("questions/type", "question_type="+question_type);

您的路线:

Route::get('questions/type', function() {
    switch(Input::get('question_type')) {
        case 1:
            return View::make("questions/type1.blade.php");
        case 2:
            return View::make("questions/type2.blade.php");
        default:
            return View::make("questions/default_type.blade.php");
    }
});

您对jQuery.load()的调用将隐式设置DOM元素的内容,ID Questions等于请求的整个输出(返回视图中包含的内容)。来自controller

  

此方法是从服务器获取数据的最简单方法。它大致相当于$ .get(url,data,success),除了它是一个方法而不是全局函数,它有一个隐式回调函数。当检测到成功的响应时(即当textStatus为“success”或“notmodified”时),。load()将匹配元素的HTML内容设置为返回的数据。

相关问题