变量在 if 语句中不可访问。语言设计?

Variable not accessible inside if statement. Language design?

所以我正在为 Go 实现 Jade 模板语言(参见 https://github.com/go-floki/jade),并且我 运行 正在使用一种有趣的 "feature" 语言。下面的代码按预期工作,为每个爆头放置 img 元素。

each $headshot in $object.Headshots
    img.img-circle.headshot(src=$headshot)

然后我想更改它,以便在第六个元素上将图像源设为预设图像。但是,当我 运行 此代码时出现错误

each $headshot, index in $cause.Headshots
    if index == 6
        img.img-circle.headshot(src="/public/images/ellipse.png")
    else
        img.img-circle.headshot(src=$headshot)

具体来说undefined variable $headshot$headshot似乎不​​存在于if语句的范围内。这不是我第一次使用此实现 运行 进入此行为,尝试变通很令人沮丧。它所带来的麻烦让我想知道,这门语言以这种方式工作可能是有原因的吗?

此外,在这种情况下,有人能想出解决 "feature" 问题的方法吗?我能想到的最好办法是稍后在客户端使用 Javascript.

更改它

首先,Go 的 if 块可以访问其封闭范围内的变量。如果这在您的示例中失败,那一定是因为您的代码或您使用的库中存在实现错误。

接下来,让我们修复贴出的代码中的一些问题:

each $headshot, index in $cause.Headshots

应该颠倒顺序——索引在前——让我们与使用$来指示变量保持一致:

each $i, $headshot in $cause.Headshots

清理完毕后,这是一个完整的演示脚本:

templates/home.玉

html
    body
        each $i, $headshot in Cause.Headshots
            if $i == 0
                img.img-circle.headshot(src="/public/images/ellipse.png")
            else
                img.img-circle.headshot(src=$headshot)

demo.go

package main

import (
    "bufio"
    "os"

    "github.com/go-floki/jade"
)

func main() {
    w := bufio.NewWriter(os.Stdout)
    // compile templates
    templates, err := jade.CompileDir("./templates", jade.DefaultDirOptions, jade.Options{})
    if err != nil {
        panic(err)
    }

    // then render some template
    tpl := templates["home"]
    tpl.Execute(w, map[string]interface{}{
        "Cause": map[string]interface{}{
            "Headshots": []string{"one", "two"},
        },
    })
    w.Flush()
}

这段代码对我有用,输出是:

<html><body><img class="img-circle headshot" src="/public/images/ellipse.png" /><img class="img-circle headshot" src="two" /></body></html>

所以我唯一的结论是你的例子中一定有其他事情发生。这可能是库中的错误,但我会首先检查以下内容:

  • jade 文件中是否混有空格和制表符?这可能会导致范围混淆
  • 我上面贴的例子是不是也报错了?如果是这样,
    • 您使用的是最新版本的 Jade 库吗?
    • 你的 Go 版本是最新的吗?