【发布时间】: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