简体   繁体   中英

Fixing Handlebars compile issue in isomorphic JS app

I'm turning an existing web app into isomorphic. 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.

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

  • If I run handlebars.compile(view)(data) on the server side I get the following error:

Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed function ret(context, execOptions) { if (!compiled) { compiled = compileInput(); } return compiled.call(this, context, execOptions); }

If this isServer ? view(data) : handlebars.compile(view)(data) isServer ? view(data) : handlebars.compile(view)(data) is working for you everywhere, you could create a function

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.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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