在JavaScript中引用Go数组。

huangapple go评论88阅读模式
英文:

Referencing Go array in Javascript

问题

我有一个 Golang 数组,我要将它传递给前端的 HTML 文件。

我知道

'{{ index .Array 0}}'

可以工作,并从数组中提取第一个元素。但是我想用 JavaScript 的 for 循环打印数组中的每个元素,像这样

<script type="text/javascript">
function loop() {

    html = ""
    for(var i = 0; i<5; i++) {
        html += "{{ index .Array " + i + "}}";
      }
}

但是这样不起作用。关于分隔 go 数组索引字符串,HTML/JavaScript 不喜欢它,它不会加载。

这是一个我无法确定的语法错误。

有什么想法吗?

英文:

I have a Golang array I'm passing to my html file on the front end.

I know that

&#39;{{ index .Array 0}}&#39; 

works and pulls the first element from the array. But I want to do a Javascript for-loop and print every element in the array like so

&lt;script type=&quot;text/javascript&quot;&gt;
function loop() {

    html = &quot;&quot;
    for(var i = 0; i&lt;5; i++) {
        html += &quot;{{ index .Array &quot; + i + &quot;}}&quot;;
      }
}

But this doesn't work. Something about separating the go array index string, HTML/Javascript doesn't like it and it won't load.

It's a syntactical error that I just can't pin down.

Any ideas?

答案1

得分: 13

你需要明白一些事情:

模板操作(例如 {{index .Array 0}})在你的 Go 应用程序的服务器端执行。

Javascript 代码在浏览器的客户端解释和运行。

模板操作中使用的模板参数值(例如你的示例中的 Array)在客户端(例如作为 Javascript 对象)中不存在。而且模板引擎不会运行 Javascript 代码。因此,模板参数(值)和 Javascript(执行)存在于两个不同的“空间”中。

也就是说,无法混合使用模板操作/变量和 Javascript 执行。

你有两个选择:

  1. 使用模板操作来完成你想要的操作。

  2. 使用模板创建在客户端执行时将数组构建/重建为 Javascript 对象的 Javascript 代码,以便进一步进行 Javascript 处理。

请注意,如果你只想循环遍历数组一次,创建一个 Javascript 数组是不必要的,你可以在 {{range}} 模板操作中直接渲染作为循环体的 Javascript 代码。可以参考 Simon 的答案 作为示例。

详细说明 #1

你可以使用 {{range .Array}} 操作来循环遍历 Array,并且该块会对每个元素执行,pipeline 设置为数组元素,因此你可以像这样输出数组元素:

{{range .Array}}
    {{.}}
{{end}}

当然,你可以在块中放入任何其他内容,不仅仅是数组元素。你甚至可以像这样访问当前索引:

{{range $idx, $value := .Array}}
    Index = {{$idx}}; Element = {{$value}}&lt;br&gt;
{{end}}

详细说明 #2

假设你的 Array 包含 int 数字,你可以使用以下模板在 Javascript 中重新创建它,并在 Javascript 中循环遍历它:

&lt;script&gt;
    var arr = [
        {{range .Array}}
            {{.}},
        {{end}}
    ];

    // 现在你有一个 javascript 数组:arr,可以循环遍历它做一些操作:
    html = &quot;&quot;;
    for(var i = 0; i &lt; arr.length; i++) {
        html += &quot; &quot; + arr[i];
    }
&lt;/script&gt;

或者,由于模板引擎支持将数组和切片“渲染”为 JavaScript 数组,你可以简单地编写:

&lt;script&gt;
    var arr = {{.Array}};

    // 现在你有一个 javascript 数组:arr,可以循环遍历它做一些操作:
    html = &quot;&quot;;
    for(var i = 0; i &lt; arr.length; i++) {
        html += &quot; &quot; + arr[i];
    }
&lt;/script&gt;
英文:

You need to understand something:

Template actions such as {{index .Array 0}} are executed at server side in your Go application.

Javascript code is interpreted and run at client side in the browser.

The template parameter value used in template actions (Array in your example) does not exist at client side (e.g. as a Javascript object). And Javascript code is not run by the template engine. So the template parameter (value) and Javascript (execution) live in 2 different "spaces".

Having said that, it is not possible to mix template actions/variables and Javascript execution.

You have 2 options:

  1. Do what you want to do with template actions.

  2. Use the template to create Javascript code which when executed at the client side will construct/recreate the array as a Javascript object so it will be available for further Javascript processing.

Note that if you just want to loop over the array once, creating a Javascript array is not neccessary, you can simply render the JavaScript code that would be the loop body inside a {{range}} template action. See Simon's answer as an example to this.

Elaborating #1

You can use the {{range .Array}} action to loop over Array, and the block is executed for each element, pipeline set to the array element so you can output the array elements like this:

{{range .Array}}
    {{.}}
{{end}}

Of course you can put anything else inside the block, not just the array elements. You can even access the current index like this:

{{range $idx, $value := .Array}}
    Index = {{$idx}}; Element = {{$value}}&lt;br&gt;
{{end}}

Elaborating #2

Let's say your Array contains int numbers, you can recreate it in Javascript and loop over it in Javascript with a template like this:

&lt;script&gt;
    var arr = [
        {{range .Array}}
            {{.}},
        {{end}}
    ];

    // Now you have a javascript array: arr, loop over it to do something:
    html = &quot;&quot;;
    for(var i = 0; i &lt; arr.length; i++) {
        html += &quot; &quot; + arr[i];
    }
&lt;/script&gt;

Or since the template engine supports "rendering" arrays and slices as JavaScript arrays, you can simply write:

&lt;script&gt;
    var arr = {{.Array}};

    // Now you have a javascript array: arr, loop over it to do something:
    html = &quot;&quot;;
    for(var i = 0; i &lt; arr.length; i++) {
        html += &quot; &quot; + arr[i];
    }
&lt;/script&gt;

答案2

得分: 3

你没有“将 Golang 数组传递给前端”..你的模板是在服务器端渲染的。这是一个重要的区别。

当你这样考虑的时候,语法问题就变得清晰了。你试图在表达式中混合使用 Go 的模板语法和 JavaScript,这是不正确的。你应该使用一个 Go 循环,在渲染时生成有效的 JavaScript 供客户端使用:

var javaScriptHtmlVariable = "";

{{ range .Array }}
    javaScriptHtmlVariable += '{{.}}';
{{ end }}

这将渲染为:

javaScriptHtmlVariable += 'One';
javaScriptHtmlVariable += 'Two';
javaScriptHtmlVariable += 'Three';
javaScriptHtmlVariable += 'Four';
// 等等...
英文:

You're not "passing a Golang array to the front end" .. your template is being rendered server side. That is an important distinction.

When you think about it like that .. the syntactic issue becomes clear. You are attempting to intermix Go's template syntax with Javascript right in the middle of expressions. That simply isn't correct. You should use a Go loop that, when rendered, produces valid Javascript for the client to consume:

var javaScriptHtmlVariable = &quot;&quot;;

{{ range .Array }}
    javaScriptHtmlVariable += &#39;{{.}}&#39;;
{{ end }}

Which would render:

javaScriptHtmlVariable += &#39;One&#39;;
javaScriptHtmlVariable += &#39;Two&#39;;
javaScriptHtmlVariable += &#39;Three&#39;;
javaScriptHtmlVariable += &#39;Four&#39;;
// etc..

huangapple
  • 本文由 发表于 2015年2月27日 03:59:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/28751637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定