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

Edw*_*oto 6 helper express handlebars.js handlebarshelper pug

使用 Pug 过滤器和 jsTransformer-handlebars 模块,我试图将一些把手代码插入到一个将使用本地人的 pug 模板中。然而,由于 Pug 在编译时渲染过滤器,我们不能使用模板 locals。所以我想知道让 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"$&');
  },
};
Run Code Online (Sandbox Code Playgroud)

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

//sets application locals so I can call these functions from a pug template
app.locals = {
  truncate,
  stripTags,
  formatDate,
  select,
};
Run Code Online (Sandbox Code Playgroud)

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

#{formatDate(story.date, 'MMMM Do YYYY')}
Run Code Online (Sandbox Code Playgroud)

但是,当尝试使用 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
Run Code Online (Sandbox Code Playgroud)

给出中断错误:

Cannot read property 'fn' of undefined
Run Code Online (Sandbox Code Playgroud)

这很可能是因为我无法像通常在车把中那样传入 options 参数:

      <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}}
Run Code Online (Sandbox Code Playgroud)

我使用把手运行了上面的程序,它按预期工作。

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

Pug 在他们的文档中对此有警告

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.
Run Code Online (Sandbox Code Playgroud)

虽然我目前有一个变通办法,但我真的很想让这个帮手与哈巴狗一起工作。我不需要特别需要能够将 locals 变量传递到车把过滤器中,因为这可能是不可能的。但是,也许我在 pug 中缺少一些可以使 select() 助手工作的东西?

我真的希望我在 pug 中遗漏了一些可以让 select() 助手工作的简单东西,或者有一种方法可以让本地人从过滤器中访问。但是,作为新手,任何帮助都值得赞赏!