[英]Append/Add Laravel blade template to current view using JavaScript
So, I have this:所以,我有这个:
item.blade.php
(locaton: 'pages/components/item.blade.php') item.blade.php
(位置:'pages/components/item.blade.php')
<div>
// some php logic
test
</div>
list.blade.php
// some laravel blade logic
<script>
function onAddItem() {
// the code above doesn't work
$.get("visitor.pages.service.html", function(data){
$('#appends').append(data);
});
}
}
</script>
<div>
<button onclick="onAddItem()">add item</button>
<div id="list">
@include('pages.components.item', ['someVars'=> false]); //this displays OK
</div>
</div>
Now what I wanna do is when I click the add item button, it should also add another pages.components.item
template inside list
(id) div.现在我想要做的是当我单击添加项目按钮时,它还应该在list
(id) div 内添加另一个pages.components.item
模板。
I already tried the answers on these posts:我已经尝试过这些帖子的答案:
But both answers don't work.但是这两个答案都不起作用。
As the answer pointed you can't do that, as blade is server side processed.正如答案所指出的那样,您不能这样做,因为刀片是服务器端处理的。 There is a workaround however but it's expensive and prone to vulnerabilities: create custom routes which output the desired blade files when needed.然而,有一个解决方法,但它很昂贵且容易出现漏洞:创建自定义路由,在需要时输出所需的刀片文件。
In routes.php
:在routes.php
:
Route::get('/blades/{path_to_blade}', function($path_to_blade){
return view($path_to_blade);
})->where('path_to_blade', '^[a-z0-9\_\-\.]+$');
Then you can use an ajax call or whatever to call the requested template.然后您可以使用 ajax 调用或任何方式来调用请求的模板。 I'm using jQuery as demo:我使用 jQuery 作为演示:
$.ajax({
url: "/blades/template.path",
cache: false,
success: function(html){
$("#element_in_which_to_insert").append(html);
}
});
You can also request the template in browser: /blades/template.path
.您还可以在浏览器中请求模板: /blades/template.path
。 But again: this method is prone to vulnerabilities.但同样:这种方法容易出现漏洞。 You should use a frontend framework such as Vue or Angular instead.您应该改用 Vue 或 Angular 等前端框架。
You should use你应该使用
function onAddInvoiceItem()
not不是
function addItem()
Because you call it with onAddInvoiceItem()
here :因为你在这里用onAddInvoiceItem()
调用它:
<button onclick="onAddInvoiceItem()">add item</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.