如何将变量从gulp传递到javascript或coffeescript资产

时间:2015-01-15 16:04:13

标签: javascript coffeescript gulp

我正在使用Coffeescript作为我的前端项目,我一直在使用Middleman,我想切换到Gulp。有了Middleman,我能做到这样的事情:

if foo is "<%= bar %>"
  # do something

其中barconfig.rb中的变量。我想用Gulp做同样的事情。有没有办法将变量和/或函数从gulpfile传递给脚本资产?

1 个答案:

答案 0 :(得分:0)

我最终使用的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

对于这种特殊情况,jade模板的替代方案是gulp-jade(类似于slim,但你可以使用vanilla jade语法而不使用gulp-templates)。

其他通用模板引擎包括:swig,mustache等......

相关问题