How can I use a handlebar variable inside a script

Asked

Viewed 790 times

1

So I’m creating a nodejs project. I’m using handlebars as my template engine and sequelize as ORM. In my route file, I create a route and send the object "status" to my form page.

(in this case, the object "state" returns me all the data from the table "State", I am using mysql)

app.get('/dashboard/formulario', (req, res) => {
    Estado.findAll().then(function (estado) {
        res.render('admin/formulario', { layout: 'admin', title: 'Formulário Administração', estado })
    })
})

in my form page I can normally read the variable using the expression {{status}}

however, I wanted to use this variable in a script, something like this:

<script>
    console.log({{estado}})
</script>

Does anyone know how I can do this? For, on the form page, this error occurs:

Uncaught Syntaxerror: Missing ) after argument list

apparently I can’t make "{{ }}" work inside the script

  • But what’s the problem? Is there an error? Have you tried using console.log("{{estado}}") quotation marks?

  • Then, on the form page, it generates this error: Uncaught Syntaxerror: Missing ) after argument list apparently "{{ }}" is not working within the script

  • This error you mentioned doesn’t seem to be related to the console.log, it seems that in some other part of your script you forgot to close parentheses. Remove the console.log completely and check if the error still happens.

2 answers

0

I don’t know, I might be talking nonsense, but I think on the page admin/formulario in Html {{ state }} is a property of handlebars. To take the same status value and use it in Javascript just make the same request you made in the other file with the form page url:

app.get('/admin/formulario', (req, res) => {
  Estado.findAll().then(function (estado) {
    let _estado = estado                              // pega os estados aqui 
  })
})

I just don’t understand why you need the object state if you are already displaying states in Html

0

Try to convert the object into a string before:

<script>
  console.log({{ JSON.stringify(estado) }});
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.