0

I am practicing fetching API data and displaying it on a web page. I am using Go to fetch quotes data from an API service. I want an additional slideshow functionality for the web page that should display another fetched quote after 5 seconds using JavaScript.

However, only one quote is displayed on the web page, and no error is logged on the browser's console. The only error my text editor displays is on the HTML file from the snippet below.

<script>
var quotes = {{.QuotesJSON}};
</script>

The following errors are being displayed:

  • Property assignment expected.javascript
  • Property destructuring pattern expected.javascript
  • Declaration or statement expected.javascript

I have tried declaring a field QuotesJSON in the data struct which is of type template.JS to indicate that the string being passed in should be treated as JavaScript code, allowing it to be safely embedded in HTML without being escaped using Go.

data := struct {
QuotesJSON template.JS
}{
QuotesJSON: template.JS(quotesJSON),
}

Where could the issue lie?

2
  • 1
    I don't know what language {{.QuotesJSON}} is, but it's not javascript. You need to assign a valid JS value to your var. Commented Dec 1, 2024 at 15:18
  • This looks like some kind of template language, so you need to process the script with that framework. Commented Dec 1, 2024 at 15:47

1 Answer 1

0

You are getting an error because {{.QuotesJSON}} is parsed as JavaScript, and your editor is correct, it is not valid JavaScript. I think what you should do instead of this is serialize the JSON into a slice of structs, then loop through each slide with a {{range .yourSlice}} statement. But if you really want to assign the resulting JSON into a variable, then you can either turn off your diagnostics or just live with the errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.