【发布时间】:2017-03-15 14:21:29
【问题描述】:
我有一个基本的 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 代码并呈现模板。
这是它返回的内容:
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>
【问题讨论】:
标签: javascript jquery laravel webpack handlebars.js