有没有办法将变量传递给PugJS过滤器

时间:2018-03-25 03:26:32

标签: express handlebars.js pug helper handlebarshelper

使用Pug过滤器和jsTransformer-handlebars模块我试图将一些把手代码插入到将使用本地人的哈巴狗模板中。但是,由于Pug在编译时渲染过滤器,我们无法使用模板本地。所以我想知道是否在浏览器上使用jsTransformer可以解决这个问题,如果是这样的话,如何打包jsTransformer-handlebars模块并使其在浏览器上可用。这是一个问题的概述(它有点长,我道歉。我想提供大量细节以保持问题清晰):

我有以下通常用于把手的辅助功能:

//helpers.js
module.exports = {
  truncate: (str, len) => {
    //code
    return str;
  },

  stripTags: input => input.replace(/<(?:.|\n)*?>/gm, ''),

  formatDate: (date, format) => moment(date).format(format),

  select: function (selected, options) {
    return options.fn(this).replace(new RegExp(` value="${selected}"`), '$&selected="selected"').replace(new RegExp(`>${selected}</option>`), 'selected="selected"$&');
  },
};

helpers.js在app.js导入,函数设置为应用程序变量。除了select()之外,它们都可以在哈巴狗中使用。

//sets application locals so I can call these functions from a pug template
app.locals = {
  truncate,
  stripTags,
  formatDate,
  select,
};

例如,任何pug模板中的以下代码都会按预期返回格式化日期:

#{formatDate(story.date, 'MMMM Do YYYY')}

但是,在尝试使用select函数时:

select(name='status' id='status')
  #{select(story.status)}
    option(value='Public' selected) Public
    option(value='Private') Private
    option(value='Unpublished') Unpublished
label(for='status') Status

给出了突破错误:

Cannot read property 'fn' of undefined

这很可能是因为我不能像通常在把手中那样传递选项参数:

      <select name ='status' id='status'>
        {{#select story.status}}
          <option value='Public' selected> Public </option
          <option value='Private'> Private </option
          <option value='Unpublished'> Unpublished </option>
        {{#/select}}

我使用把手跑了上面,它按预期工作。

然后我的下一个解决方案是使用哈巴狗过滤器将把手代码插入哈巴狗。但是,在尝试此操作时,变量不会在过滤器中生成。当然,这是因为帕格在编译时呈现过滤的代码,因此变量/局部变量永远不会传递到手柄代码中。

帕格在documentation

上发出警告
Warning
Filters are rendered at compile time. This makes them fast, but it also means that they cannot support dynamic content or options.

By default, compilation in the browser does not have access to JSTransformer-based filters, unless the JSTransformer modules are explicitly packed and made available through a CommonJS platform (such as Browserify or Webpack). In fact, the page you are reading right now uses Browserify to make the filters available in the browser.

Templates pre-compiled on the server do not have this limitation.

虽然我目前有一个解决方法,但我真的很想让这个助手与帕格一起工作。我没有特别需要能够将locals变量传递到把手过滤器,因为这可能是不可能的。但是,也许有些东西我会被帕格所遗漏,这会使select()助手工作?

我真的希望我错过了一些简单的哈巴狗,这会使select()助手工作,或者有一种方法可以让过滤器内的本地人可以访问。但是,作为一个新手,任何帮助都表示赞赏!

0 个答案:

没有答案
相关问题