Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - Node.js with Handlebars.js on server and client

I have an app in Node.js using Expressjs and Handlebars as the template engine.

Expressjs uses layouts and then renders views. The layout (layout.hbs) looks like this:

<!doctype html>
<html lang="en">
    <head>
    </head>
  <body>
    {{{body}}}
  </body>
</html>

The {{{body}}} is replaced server-side, within node.js when you access a route. For example:

app.get('/', function(req, res){
   res.render('index'})
})

Will replace the {{{body}}} tag with the contents of index.hbs.

Now, on the client side I'm using Backbone.js and want to use Handlebars for the views controlled via Backbone. The problem is that because these pages are already rendered through Handlebars, when I attempt to use Handlebars within it (or Handlebars within Handlebars) it doesn't work. There are no errors, it simply just doesn't replace tags with data.

Has anyone encountered this before or have any idea a work around?

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use pre-compiled client templates. They are faster executing and allow you to use the same template language on the server and client.

  1. Install handlebars globally npm install handlebars -g
  2. Precompile your templates handlebars client-template1.handlebars -f templates.js
  3. Include templates.js <script src="templates.js"></script>
  4. Execute the template var html = Handlebars.templates["client-template1"](context);

https://stackoverflow.com/a/13884587/8360


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...