将函数传递给 Pug 模板,以便在 Javascript 前端通过回调使用

Pass function to Pug template to be used via callback in Javascript frontend

我正在尝试将函数(timeAgo 模块)传递到我的 Pug 模板,以便在回调期间在我的前端 Javascript 中使用。

但是,我尝试的任何方法组合都无法使模块在回调期间工作。如果我在编译前端时使用它,它当然可以正常工作,但我无法将模块作为函数加载到脚本标记中,以便我可以再次使用它。

所以:

p.balance-text #{timeAgo.format(new Date(story.publishedAt))}

工作正常,但我该怎么做:

script. 
  // this allows me to use it to format dates received via an AJAX request
  var  timeAgo = #{timeAgo}

我也尝试过使用 JSON.stringify 将其传递到前端,但似乎没有任何效果。哈巴狗有可能吗?谢谢

你不能。

您正在生成 HTML 源代码。所以一切都需要能够转换为字符串。

I've also tried things like using JSON.stringify

这也是 JSON 没有函数数据类型的原因。

生成一个带有 src 属性的 <script> 元素,用于在静态文件中加载模块。 (如果它是 ES6 模块,那么要么使用 <script type="module">import 代替,要么使用 Webpack)。