我在前端项目中使用 Coffeescript,到目前为止我一直在使用 Middleman,现在我想切换到 Gulp。通过 Middleman,我可以做这样的事情:
if foo is "<%= bar %>"
# do something
其中bar
是config.rb
中的变量。我想使用 Gulp 做同样的事情。有没有办法将变量和/或函数从 gulpfile 传递到脚本 Assets ?
最佳答案
我最终使用了 gulp-template
编译 lodash templates看起来与 erb
几乎相同。让我们以 slim
为例。模板,通常如下所示:
doctype html
html
head
title = project_title
body
#content
- if html5?
p Routes look like "example.com/some/route"
- else
p Routes look like "example.com/#!/some/route"
#footer
| Copyright © #{year} #{author}
现在翻译为:
doctype html
html
head
title <%= projectTitle %>
body
#content
<% if isHtml5() { %>
p Routes look like "example.com/some/route"
<% } else { %>
p Routes look like "example.com/#!/some/route"
<% } %>
#footer
| Copyright © <%= year %> <%= author %>
注意 <% .. %>
之间的代码不再是 ruby,而是普通的 javascript。您可以按照您想要的任何疯狂组合使用它,但您必须仔细考虑那里的输出:if .. else
之间没有缩进差异。和段落,正如您对超薄模板所期望的那样。
要将数据公开给模板,请将对象传递给 gulp-template
像这样:
var gulp = require('gulp');
var template = require('gulp-template');
var slim = require('gulp-slim');
gulp.task('slim', function () {
return gulp.src('src/*.slim')
.pipe(template({
projectTitle: 'Example',
year: '2015',
author: "Master Yoda"
isHtml5: function(){
// ...
}
}))
.pipe(slim({pretty: true}))
.pipe(gulp.dest('dist'));
});
可以在此处找到文档:https://github.com/sindresorhus/gulp-template
对于这种特殊情况,替代方案是 gulp-jade
用于 Jade 模板(类似于 slim,但您可以使用普通的 Jade 语法而不使用 gulp-templates
)。
其他通用模板引擎包括:swig、mustache 等...
关于javascript - 如何将变量从 gulp 传递到 javascript 或 Coffeescript Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967709/