【问题标题】:How can I separate gulp-template code from underscore template code?如何将 gulp-template 代码与下划线模板代码分开?
【发布时间】:2015-06-01 14:44:50
【问题描述】:

我正在使用 gulp 来构建我的项目,并且我的项目的一部分使用了 Underscore 模板。我在构建过程中使用的插件之一是 gulp-template,它使用 Lodash 模板。

是否可以指出当我使用 gulp 时应该渲染哪些代码,以及在模板中应该忽略哪些代码?

例如,我有一个文件包含:

<script src="<%= image_server_url %>/scripts/iep-alert/alert-content.js"></script>

在构建期间,我希望呈现 image_server_url。但是,在我的项目的其他地方,我有这段代码,我想被 gulp-template 插件忽略:

<%
    if(alert.disability === "true") {
%>
    <li><span style="font-weight: bold;">Disability: </span><%= alert.disability %></li>
<%
    }
%>

现在,当我调用调用 gulp-template 的 gulp 任务时,我得到 ReferenceError: alert is not defined,因为 gulp-template 的上下文不包括 alert - 只有 image_server_url 是 gulp 上下文的一部分-模板。

编辑:我已编辑我的代码以匹配 {{ image_server_url}},并将我的调用更改为 gulp-template,如下所示:

template({
    image_server_url: config.dev.image_server_url
}, {
    interpolate: /{{([\s\S]+?)}}/g
})

通过这些更改,当我运行 build 任务时,我认为 gulp-template 仍在尝试在 &lt;%%&gt; 块中运行代码,因为我收到了这个错误:

window is not defined

它试图在第一个 &lt;% JS block %&gt; 中运行的代码

<%
    if (window.location.href.indexOf('admin') != -1) {
%>

如果有人能解决这个特定问题,那就太好了。我想现在我要研究一个替代解决方案。

【问题讨论】:

    标签: javascript templates underscore.js gulp lodash


    【解决方案1】:

    我找不到明智的方法来做到这一点,因为你想解析 same 模板两次,只有一些字符串必须在 gulp 中插值,其他在浏览器。

    一个建议是使用_.templateSettings,这样在gulp处理中,可以使用其他的模板格式。

    以 gulp 为例,您可以设置:

    _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;

    在你的模板中:

    &lt;script src="{{ image_server_url }}/scripts/iep-alert/alert-content.js"&gt;

    因此,当模板打算由 gulp 处理时,使用 {{}} 插值语法,而当它打算在浏览器端处理时,使用默认 (erb) &lt;%= %&gt; 语法。

    【讨论】:

    • 在哪里设置interpolate?那是在我的gulpfile 的某个地方吗?
    • 因为我只使用 gulp-template 插件来插入字符串,有没有比使用像 Lodash 这样的完整模板系统更好的方法来解决这个问题?
    【解决方案2】:

    我最终使用了gulp-preprocess 插件。我的代码现在看起来像这样,到目前为止运行良好。

    <script src="<!-- @echo IMAGE_SERVER_URL -->/scripts/iep-alert/alert.js"></script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2022-01-06
      • 2020-11-04
      • 2018-03-31
      • 2018-10-30
      • 1970-01-01
      • 2012-04-02
      相关资源
      最近更新 更多