【问题标题】:multiple pass variable replacements with handlebars?用车把多次通过变量替换?
【发布时间】:2021-06-06 13:27:18
【问题描述】:

我还没有找到合适的答案,所以我想我会尝试。

用例。我有需要 2 次处理的 HTML 文件。其中一个有静态变量,但我需要在编译时将它们替换为多层(开发、中介、生产)的固定值。

我还有一组变量,当下载这样的模板时,它们将被替换,这将是第二遍。

<!DOCTYPE html>
<html>
  <head>
    ...stuff
  </head>
  <body>
    <h1>Hello {{ReplaceOnCompile}}</h1>
    <a href="{{ReplaceOnRuntime}}">Some Link</a>
  </body>
</html>

据我所知,Handlebars 没有提供任何开箱即用的方法来执行此操作。我目前使用以下系统工作:

// Create handlebars object from template
const template = await compile(rawFileContents)

// Replace template with variables
const html = await template({
  ReplaceOnRunTime: 'foo'
})

这一切都很好,花花公子,但这给我留下了:

<!DOCTYPE html>
<html>
  <head>
    ...stuff
  </head>
  <body>
    <h1>Hello </h1>
    <a href="foo">Some Link</a>
  </body>
</html>

我在它的文档中没有看到任何支持自定义分隔符/包装器表达式来执行第一遍/第二遍的事情。

我的下一个想法是使用sed 或仅使用这样的包来进行第一遍替换: https://www.npmjs.com/package/replace-in-file

并且在模板中,对每种类型的变量使用不同的语法来替换:

<!DOCTYPE html>
<html>
  <head>
    ...stuff
  </head>
  <body>
    <h1>Hello {<<ReplaceOnCompile>>}</h1> // Pass this through one replacement func
    <a href="{{ReplaceOnRuntime}}">Some Link</a> // Pass this through a second one.
  </body>
</html>

不确定最好的方法,因为我试图避免使用两个不同的库来完成基本相同的任务,只是交错。

【问题讨论】:

    标签: javascript sed replace handlebars.js mustache


    【解决方案1】:

    这对我来说似乎是一个奇怪的用例,但是,我想我可以通过将运行时变量的值设置为 Handlebars 表达式来解决它,确保保留变量名。

    这意味着在模板的第一次执行中使用的数据对象将包括以下内容:

    ReplaceOnRuntime: "{{ReplaceOnRuntime}}"
    

    这意味着我的模板中的 {{ReplaceOnRuntime}} 将被替换为“{{ReplaceOnRuntime}}” - 换句话说,此表达式的模板输入和输出将是相同的。

    我创建了一个示例fiddle 供参考。

    【讨论】:

    • 我知道你打算用这个去哪里。是的,用例是当我们保存模板时我需要动态替换一些初始变量,而其他的在我们使用模板时填充帐户特定的东西。
    【解决方案2】:

    我找到了一种巧妙的方法来逃避它们!

    https://repl.it/@nicholashazel/TriflingMeanLogin

    您可以转义一个车把表达式并让它输出原始的{{variableName}},只需使用反斜杠即可。

    通过 1

    <body>
      <h1>{{ReplaceMe}}</h1>
      <p>\{{DontReplaceMe}}</p>
    </body>
    
    const variables = {
      ReplaceMe: 'Replaced in pass 1'
    }
    const template = await handlebars.compile(data)
    const html = await template(variables)
    
    <body>
      <h1>Replaced in pass 1</h1>
      <p>{{DontReplaceMe}}</p>
    </body>
    

    通过 2

    const newVariables = {
      DontReplaceMe: 'Replaced in pass 2'
    }
    const newTemplate = await handlebars.compile(html)
    const newHtml = await newTemplate(newVariables)
    
    <body>
      <h1>Replaced in pass 1</h1>
      <p>Replaced in pass 2</p>
    </body>
    

    【讨论】:

      猜你喜欢
      • 2015-08-26
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多