简体   繁体   English

修复同构JS应用中的把手编译问题

[英]Fixing Handlebars compile issue in isomorphic JS app

I'm turning an existing web app into isomorphic. 我正在将现有的Web应用程序变成同构的。 I've created a proof of a concept to play around with the dependencies that you can check here . 我已经创建了一个概念证明,可以处理您在这里可以检查的依赖关系。 The issue is: Handlebars compile() behaves different on the server and on the client side because of the templates are required/imported differently on these platform. 问题是:把手compile()在服务器和客户端上的行为不同,因为在这些平台上需要/导入的模板不同。

var view = require('someView.hbs');
var data = {};
var content = isServer ? view(data) : handlebars.compile(view)(data);

In the existing app I'd need to rewrite a lot of code by injecting the condition above .. Is there a better way to unify this, get rid of the condition? 在现有的应用程序中,我需要通过注入上面的条件来重写很多代码..是否有更好的方法来统一此条件,摆脱该条件? How to make the templates imported the same way on both sides? 如何使模板在两侧以相同的方式导入?

Some more info: 更多信息:

  • I use stringify: require('stringify') 我使用stringify: require('stringify')

  • If I run handlebars.compile(view)(data) on the server side I get the following error: 如果我在服务器端运行handlebars.compile(view)(data) ,则会出现以下错误:

Error: You must pass a string or Handlebars AST to Handlebars.compile. 错误:您必须将字符串或Handlebars AST传递给Handlebars.compile。 You passed function ret(context, execOptions) { if (!compiled) { compiled = compileInput(); 您传递了函数ret(context,execOptions){如果(!compiled){编译= compileInput(); } return compiled.call(this, context, execOptions); 返回已编译的调用(this,context,execOptions); } }

If this isServer ? view(data) : handlebars.compile(view)(data) 如果这是isServer ? view(data) : handlebars.compile(view)(data) isServer ? view(data) : handlebars.compile(view)(data) is working for you everywhere, you could create a function isServer ? view(data) : handlebars.compile(view)(data)随处可用,您可以创建一个函数

var my_render = function(view,data) {
  return isServer ? view(data) : handlebars.compile(view)(data);
}

and then put content = my_render(view,data) where you need. 然后将content = my_render(view,data)放在您需要的位置。


Perhaps a better solution is: 也许更好的解决方案是:

var my_compiled_hb = isServer ? view : handlebars.compile(view);

and then use content = my_compiled_hb(data) where you need. 然后在需要的地方使用content = my_compiled_hb(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM