【问题标题】:How to use continue and break keywords in golang templates?golang模板中如何使用continue和break关键字?
【发布时间】:2023-03-04 11:47:01
【问题描述】:

例如:

{{range .Users}}
    {{if .IsAdmin}}
        {{/* How to use "break" or "continue"? */}}
    {{end}}
{{end}}

golang.org 中没有模板中“中断”或“继续”的文档

【问题讨论】:

标签: go-templates


【解决方案1】:

它们没有记录,因为它们不存在。

为了确保 - 检查 text/template lexer 的测试:https://github.com/golang/go/blob/master/src/text/template/parse/lex_test.go

【讨论】:

  • 但是我怎样才能做到这一点呢?还有其他方法吗?
  • 你不能模拟break,也不需要continue,只要你有{{if。 Golang 模板不适合逻辑太复杂。
  • 您能否分享一个关于如何跳过或停止迭代的示例?
  • 您无法停止迭代。但是您可以使用简单的{{if .IsAdmin}} 跳过。 {{if }} 中的内容只有在条件为真时才会呈现。
  • 好的,我明白了。谢谢。
【解决方案2】:

Go101 does mention(2021 年 5 月,4 年后):

从 Go 1.18 开始,Go 模板的范围循环可能支持“break”和“continue”。

注意:Go 1.18 应该在 2022 年第一季度发布。

这将解决 issue 20531 文本/模板:添加 breakcontinue 支持。
并且目前在CL 321491中实现:html/templatetext/template:实现breakcontinue for range循环。

目前这项工作仍在进行中(2021 年第一季度)

2021 年 9 月更新:confirmedcommit d0dd26a

html/templatetext/template:实现 breakcontinue for range 循环

breakcontinue 用于范围循环在 2017 年 6 月被接受为提案。
它在CL 66410(2017 年 10 月)中实施
但随后在 CL 92155(2018 年 2 月)回滚,因为 html/template 更改尚未实施。

这个 CL 在 text/template 中重新实现了 break 和 continue,然后也在 html/template 中添加了对它们的支持。

【讨论】:

    【解决方案3】:

    breakcontinue 语句是 Go 1.10 中 text/templatehtml/template 的一部分(在撰写本文时为 Beta 版)。来自release notes

    {{break}}{{continue}} 新动作突破最深处 {{range ...}} 循环,就像对应的 Go 语句一样。

    Go 的早期版本(1.10 之前)支持 breakcontinue 语句。

    查看 beta 文档,您可以在 lexer 中看到新的 itemContinueitemBreak 项,Parser 中的新节点如 ContinueNode 遵循代码。

    【讨论】:

    • 新的 break 和 continue 操作在 html/template 中不起作用,修复它们需要考虑在发布的这个阶段似乎太棘手的安全问题。我们将在 1.11 再次尝试。 github.com/golang/go/commit/…
    【解决方案4】:

    您可以使用变量添加处理中的检查并跳过循环剩余部分的任何现有检查。

    // method 1
    {{ $dothing := false }}
    {{ range $i, $A := .List }}
      {{ if $A.Check }}
        {{ $dothing = true }}
      {{end}}
    {{ end }}
    {{ if $dothing }}
      // do thing
    {{ end }}
    
    // method 2
    {{ $already := false }}
    {{ range $i, $A := .List }}
      {{ if $already }}
      {{ else }}
        {{ if $A.Check }}
          {{ $already = true }}
          // do thing
        {{ end }}
      {{ end }}
    {{ end }}
    
    
    

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 2014-03-07
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 2023-03-17
      • 2013-10-13
      相关资源
      最近更新 更多