"如何替换"车把帮手工作?

时间:2016-04-22 19:08:26

标签: replace handlebars.js bigcommerce helpers

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

npm&#39的文档示例:

{{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)

1 个答案:

答案 0 :(得分:1)

我认为您正在查看错误 replace帮助程序的文档。您使用的帮助程序库来自BigCommerce,其replace帮助程序是Handlebars Block Helper。使用它的方法是:

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

修改

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

关于在目标字符串(haystack)中找不到要替换的字符串(针)时没有输出的后续操作:事实证明这是帮助程序的设计行为。我检查了source code,我可以确认它实现了以下规则:

  • 如果大海捞针包含针头,则返回干草堆,更换针头的所有实例。
  • 如果haystack 包含针,请返回帮助者的else分支。

这意味着如果我们想显示任何输出,比如原始的haystack,当大海捞针中没有针的匹配时,那么我们必须在模板中使用else分支:

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

说实话,这似乎是对这个助手的一个非常尴尬的实现。