我有一个基本的 Laravel 项目,一个 todo 应用程序,并且我使用 Laravel Elixir 编译资产,我使用 handlebars-loader
为 Webpack 编译我的资产。
这是我的 gulpfile.js:
const elixir = require('laravel-elixir');
elixir((mix) => {
mix.webpack('app.js', null, null, require('./webpack.config.js'));
});
我正在要求 webpack.config.js,因为我想加载 handlebars-loader。
这是我的 webpack.config.js:
module.exports = {
module: {
loaders: [
{ test: /\.handlebars$/, loader: "handlebars-loader" }
]
},
};
为了更方便地回答这个问题,我将把所有代码都放在app.js中:
'use strict';
var _token = $('meta[name="csrf-token"]').attr('content');
var renderErrorsTemplate = require('./../templates/errors.handlebars');
var renderTasksTemplate = require('./../templates/task.handlebars');
$('#taskForm').submit(function(event) {
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
});
request.done(function(response) {
renderTasks(response);
});
request.fail(function(response) {
renderErrors(response.responseText);
});
event.preventDefault();
});
function renderTasks(response) {
var response = {task: response, token: _token};
$('#tasks').append(renderTasksTemplate(response));
console.log(renderTasksTemplate);
}
function renderErrors(response) {
$('#errors').html(renderErrorsTemplate(JSON.parse(response)))
console.log(renderErrorsTemplate(response));
}
我正在使用
require('template.js')
来引用所需的模板,不使用 Laravel Elixir,它可以在没有任何框架的另一个纯应用程序中工作,但是如果我在终端中运行gulp
,它会将其编译成 JavaScript 代码,所以当我使用单击事件触发函数时,它只返回一些 JavaScript 代码,而不是实际运行该 JavaScript 代码并呈现模板。这是它的返回结果:var Handlebars = require("/home/akar/Code/laravel-app/node_modules/handlebars/runtime.js"); function __default(obj) { return obj && (obj.__esModule ? obj["default"] : obj); } module.exports = (Handlebars["default"] || Handlebars).template({"1":function(container,depth0,helpers,partials,data) { return "
" + container.escapeExpression(container.lambda((depth0 != null ? depth0["0"] : depth0), depth0)) + "
\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "
\n
\n" + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},depth0,{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
\n
"; },"useData":true});
与其使用此模板的处理版本:
<div class="alert alert-danger">
<ul>
{{#each this}}
<li>{{ this.[0] }}</li>
{{/each}}
</ul>