Html template value in script

Hello,

I see some examples of html template script with values but i get an error. For example, in this site, https://www.calhoun.io/intro-to-templates-p1-contextual-encoding/, gives this example,

{{.Title}}
{{.HTML}}
{{.SafeHTML}}
{{.}}


<a title="{{.Title}}">
<a title="{{.HTML}}">

<a href="{{.HTML}}">
<a href="?q={{.HTML}}">
<a href="{{.Path}}">
<a href="?q={{.Path}}">

<!-- Encoding even works on non-string values! -->
<script>
  var dog = {{.Dog}};
  var map = {{.Map}};
  doWork({{.Title}});
</script>

In he can put values {{.}} but in my IDE i get this error: [js] Declaration or statement expected.

Is it possible to inject directly values in scripts? If not, what is the best way?

Thanks

The [js] part seems as if your “smart” IDE tries to check this as HTML with embeded JavaScript. Turn that check off, it can’t work with template files, as they often only contain partial or invalid HTML and JavaScript before the actually got rendered.

1 Like

Thanks

What editor are you using? And is your code the same as mine? I’d like to try to replicate it locally so I can add a note to the article so others don’t get confused as well :slight_smile:

I use VS Code and to solve this for me, thanks to NobbZ, is to set up “html.validate.scripts”: false, but there is one problem, the VS Code formater tool is going to cascade the code and in the browser console you can see that error. Or you remove html formater in html files, or, what i did, change the name to *.gohtml (you also lose the formater)

Good luck

I prefer to use the regular file ending of the template target followed by the suffix of the template language.

Let’s say I want to generate index.html from the template I’d save the template as index.html.gotpl.

For Emacs I have a mode that knows about this convention and highlights appropriately.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.