Ben Botvinick
Ben Botvinick

Reputation: 3345

Use Handlebars.js context from within <script> tag

I am trying to use context variables set on an Express backend using Handlebars.js (express-handlebars on npm) as the view controller from within a <script> tag. I read this post but the answer seemed to be a bit of a hack. Here's the problem in code:

app.js (server)

app.get('/', (req, res) => {
  res.render('index', {
    data: [1, 2, 3]
  }
}

index.handlebars

<script>
  const data = {{data}}
</script>

<script src="js/index.js"></script>

index.js (client)

console.log(data)

I am doing this so that I can access the data variable from index.js, so a better way of doing that would solve this problem.

Upvotes: 0

Views: 1586

Answers (1)

iwaduarte
iwaduarte

Reputation: 1699

Unfortunately this is the only way if you need to send html as a response using handlebars templating in one go.

Server side rendering creates a complete page and all your data should be "parsed" and ready.

You could circumvent this by using AJAX request (note that this adds a second request) and return a JSON response from there you could just handle it (recommended way):

//somewhere in your page.hbs

    <script>
      const loadObject = () => fetch('/express/path')
                                 .then(response => response.json)
                                 .then(obj => {
                           //do whatever with the obj
    })
      window.onload = loadObject; 

    </script>

And in your express.

  app.get('/express/path', (req, res) => {
      res.json({
        data: [1, 2, 3]
      })
    })

You can also use a <script src=/express/to/javascript > to request a specific .js file. And from there use any global scope variable. You can see a good discussion in the link below:

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Upvotes: 1

Related Questions