if语句中无法访问变量。语言设计?

时间:2016-02-20 00:31:06

标签: go syntax scope pug

所以我正在使用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。似乎$headshot声明范围内不存在if。这不是我第一次使用此实现遇到此行为,尝试解决此问题令人沮丧。我遇到的麻烦让我想知道,语言是否有可能以这种方式运作?

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

1 个答案:

答案 0 :(得分:2)

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

接下来,让我们解决发布的代码中的一些问题:

each $headshot, index in $cause.Headshots

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

each $i, $headshot in $cause.Headshots

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

模板/ home.jade

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库吗?
    • 你的Go版本是最新的吗?