"replace" 车把助手如何工作?

How does the "replace" handlebars helper work?

当分面名称包含特殊字符时,分面搜索会给我带来问题 - 特别是 /()。我正在尝试使用 Stencil 内置的 handlebars 助手替换特殊字符。每当我使用 replace 车把助手时,我总是收到 500 错误。

npm 的文档示例:

{{replace "Liquid Snake" "Liquid" "Solid"}}

即使使用那段代码(简单的字符串,而不是变量),我也会收到 500 错误。

这是日志:

Debug: internal, implementation, error 
TypeError: Uncaught error: options.inverse is not a function
at Object.<anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/helpers/replace.js:19:28)
at Object.template.1 (eval at <anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/index.js:71:44), <anonymous>:11:72)
at Object.prog [as fn] (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/handlebars/dist/cjs/handlebars/runtime.js:193:15)
at Object.<anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/helpers/if.js:85:28)
at Object.template.main (eval at <anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/index.js:71:44), <anonymous>:70:35)
at Object.ret [as components/faceted-search/facets/multi] (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/handlebars/dist/cjs/handlebars/runtime.js:159:30)
at Object.<anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/helpers/dynamicComponent.js:32:50)
at Object.template.7 (eval at <anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/index.js:71:44), <anonymous>:33:109)
at Object.prog [as fn] (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/handlebars/dist/cjs/handlebars/runtime.js:193:15)
at Object.<anonymous> (/Users/theuser/.nvm/versions/node/v4.4.0/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@bigcommerce/stencil-paper/helpers/if.js:85:28)

我认为您正在查看 错误 replace 助手的文档。您正在使用的帮助程序库来自 BigCommerce and its replace helper is a Handlebars Block Helper。使用方法是:

{{#replace "Liquid" "Liquid Snake"}}Solid{{/replace}}

编辑

感谢您指出我在示例中错误地将替换字符串括在小胡子括号中。我在原始代码块中将 {{"Solid"}} 替换为 Solid,因此示例现在是正确的。

关于你后续关于在目标字符串(大海捞针)中找不到要替换的字符串(针)时没有输出的问题:原来这是helper的设计行为.我检查了 source code,我可以确认它实现了以下规则:

  • 如果大海捞针里有针,return 大海捞针的所有实例都被替换了。
  • 如果大海捞针没有针,return帮手的else分支

这意味着如果我们想要显示任何输出,就像原始的大海捞针一样,当大海捞针中没有匹配的针时,我们必须在我们的模板中使用 else 分支来实现:

{{#replace "Liquid" "Liquid Snake"}}Solid{{else}}Liquid Snake{{/replace}}

说实话,这个助手的实现看起来确实很笨拙。