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



所以我正在使用 Go 的 Jade 模板语言的实现(见 https://github.com/go-floki/jade),我遇到了该语言的一个有趣的"功能"。下面的代码按预期工作,为每个爆头放置和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.似乎$headshotif声明的范围内不存在。这不是我第一次使用此实现遇到这种行为,尝试解决方法令人沮丧。它带来的麻烦让我想知道,语言以这种方式工作可能有什么原因吗?

此外,在这种情况下,任何人都可以想到一种解决"功能"的方法吗?我能想到的最好的办法是稍后使用Javascript在客户端更改它。

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

接下来,让我们修复已发布代码中的一些问题:

each $headshot, index in $cause.Headshots

顺序应该颠倒过来 - 索引首先 - 让我们与使用$来指示变量保持一致:

each $i, $headshot in $cause.Headshots

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

模板/首页.翡翠

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)

演示去

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 文件中是否有空格和制表符的混合?这可能会导致范围混淆
  • 我上面发布的示例是否也给您一个错误?㞖
    • 您使用的是最新版本的翡翠库吗?
    • 您的 Go 版本是最新的吗?

最新更新